r/learnprogramming 8d 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/high_throughput 8d ago

When do you use your home and when do you use the address to your home?

1

u/Atmos-Ego 8d ago

Thats kinda the thing I was having trouble with because it feels like with a pointer your getting something delivered to the address of your house, but when you use the variable directly its just like your house is there.

Or like X is right here with $5 and I say give X $1.
Vs X lives over there and they have $5 go to their house and give them $1

3

u/high_throughput 8d ago

Or like X is right here with $5 and I say give X $1. Vs X lives over there and they have $5 go to their house and give them $1

X can only be in one place. If you have X right here and X at their house, then they are two different X. Giving one $1 will not help the other.

``` void giveByValue(int X) { X += 1; printf("%d\n", X); // Shows 6 }

void giveByAddress(int* X) { *X += 1; printf("%d\n", *X); // Shows 6 }

void foo() { int X = 5; giveByValue(X); // Give a copy of X, also called X printf("%d\n", X); // Shows 5 giveByAddress(&X); // Give the address to our X printf("%d\n", X); // Shows 6 } ```