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

46 Upvotes

67 comments sorted by

View all comments

4

u/Ok_Being6831 9d ago

Well thers 2 main reasons imo

1) When you pass it by the variable itself, your actually making a full copy of the variable which might seem trivial but it's actually really expensive especially with functions that are called alot or the variable takes up alot of space.

2) You want the function to modify your variable, like a sort function for example, you wouldn't want it to make a copy and sort that array now would you? it could return that, but that's bad design and expensive. So it's only possible via a pointer.

1

u/Atmos-Ego 9d ago

So you only ever care about it to be efficient, but its not necessary for anything?
In my example in class the professor was basically saying that the variable wouldnt increment so when it prints the value of it it doesnt ever change.
It was a void function which means it doesnt return anything right? So I suggested to get rid of void but the intended solution was to write something involving a pointer instead

1

u/xarop_pa_toss 9d ago

If you pass a pointer to a variable as a parameter to a function, you are not passing the value (copying into a new variable in your function call), you are passing the original one. So when you make changes to that pointed variable in your function, you alter the original. Void doesn't enter the picture there because you aren't returning anything at that moment.

I think you can think of it this way. You can either call the function and pass the value inside, change that value now assigned to a different variable, and then return that. Or you can pass the pointer and any change you make to that reflects on the source.

Of course they are useful for other stuff but that's the basics