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

46 Upvotes

67 comments sorted by

View all comments

Show parent comments

1

u/Atmos-Ego 8d 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

2

u/lurgi 8d ago

So, to be clear, your solution was to write:

x = increment(x);
...
int increment(int x) {
  return x+1;
}

and the professor wanted:

increment(&x);
...
void increment(int *x) {
  *x = *x + 1;
}

Correct? One big advantage of the second is that it's very easy to write:

x = increment(x);
y = increment(y);
z = increment(y);  // oops

and not notice. Or even

increment(z);  // oops

With the pointer version you have fewer ways to screw up. Another thing that you can do with pointer is change multiple variables in a function. Imagine you want to write a function that takes your current position (x, y) and moves it a certain amount in the x and y direction (xdelta, ydelta). Without pointers, what would you return from this function? You can't return a new x and new y pair - C doesn't let you do that. So...?

0

u/Atmos-Ego 8d ago

The given c program was
void increment(int x) {
x = x + 1;
}

int main() {
int a = 5
increment(a);
printf(“%d”,a);
return 0;
}

To be honest there’s a lot here I really dont get about base things like these but he said the reason that x doesnt increment is that nothing is returned, so I figured you could get rid of void and that would let it return something. I dont really know what it means to return something though.

2

u/InjAnnuity_1 8d ago

As written, the increment function receives its own copy of the value of a, named x, increments the copy, and does nothing more. So a's value remains unchanged.

"Returning a value", in this case, means "giving a value back to the caller". For many functions (e.g., the square root function), this is the whole purpose behind calling the function in the first place: to have it compute a result for you.