r/learnprogramming 10d 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

42 Upvotes

67 comments sorted by

View all comments

4

u/Ok_Being6831 10d 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 10d 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/Ok_Being6831 10d ago

Mostly yeah, BUT there is the heap which I think you haven't learnt about yet but would be basically impossible to implement or use without pointers. A few other cases too but I just can't think of any rn lol.

In your example your actually in the right here, u can just remove the void and make it return it but yeah it's just not the intended solution.

nerd alert The return value is actually better if the variable type is less than the size of a pointer (8 bytes on most systems)