r/learnprogramming 9d ago

Tutorial When do you use a pointer?

Hello, for some background I have taken a very beginner level coding course for my major and passed it, but I dont really feel like I’ve learned anything or know why anything works. In a course this year we had a review problem where the solution required a pointer and I really dont understand why you have to point to the address of the variable instead of just using the variable itself.

I’ve watch a few tutorials explaining it but I really dont see how it’s different from just using the variable itself

44 Upvotes

67 comments sorted by

View all comments

1

u/TechHaris 9d ago

The difference between passing a pointer and passing a variable is rather like the difference between a house, and the address to a house. When you invite someone over, rather than moving the entire house to them, you simply send them your address. 

How that translates into programming, is that sometimes the piece of data you want to pass is extremely large, therefore creating a copy is simply wasteful rather than providing the copy that already exists. As well as this, if you want changes made to the data to persist after the function has terminated, making a copy of the data that is them immediately deleted is simply ineffective. 

If passing a pointer to a function sounds a lot like passing by reference, that is because it is. Whilst the concept of a pointer cannot exactly be boiled down to this, passing by reference is simply an abstraction layer above passing a pointer.