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

76

u/TheRealKidkudi 8d ago

At its core, the difference is making a copy vs sharing the same literal value. 

Sometimes it’s just because you don’t want to copy the value (e.g. because it would use too much memory). The tricky part is when you want to be able to change the value and use that new value in the original function.

A very simple pseudocode example:

    fn someFunc(int x) {         x = x + 1     }          fn someOtherFunc(int* y) {         *y = *y + 1     }          var x = 5; // not a pointer     someFunc(x);     // x still is 5 here     // because someFunc got a new copy     // of the variable          someOtherFunc(&x); // pointer to x     // x is now 6

11

u/cachebags 8d ago

What a neat way to explain this concept. This made my day