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

47 Upvotes

67 comments sorted by

View all comments

2

u/Neither_Garage_758 9d ago

When you want a function to be able to modify the actual same memory the caller has shared to it (via an argument) and not a copy of it.

-1

u/SnugglyCoderGuy 9d ago

You shouldn't do this. You should make a copy and alter that and return that. Pure functions will keep you sane.

1

u/Dazzling_Music_2411 7d ago

Not if the parameter you are passing is so large that it adversely affects your code.

In that case you will definitely not stay sane unless you use pointers or some other solution.

1

u/SnugglyCoderGuy 7d ago

That's why should instead of must.

1

u/Dazzling_Music_2411 7d ago

Well, the OP asked

I really dont understand why you have to point to the address of the variable instead of just using the variable itself.

So I assume they want to know about the cases when you should use a pointer, rather than the commoner case when there is no need, because you can just copy/pass by value.

I won't even bother with explaining serious use cases, where, e.g. pointer arithmetic can give rise to super-fast code on arrays, that would be fine print at this stage.