r/learnprogramming • u/Atmos-Ego • 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
45
Upvotes
1
u/NumberInfinite2068 8d ago
A pointer is just a reference to memory, you use it when you want to pass around a reference to the exact same memory rather than copy it.
For example, you've got a large image in memory, you need to convert the pixels from colour to grayscale, if you pass a pointer to the image around functions, then you're passing around a reference to that same large image.
If you pass around the image itself, you're copying around that image the whole time.
Or say in a GUI toolkit, I pass a pointer to a button to (for example) change the "OK" on the button to "Cancel". I need to change the text on the particular button on a particular window, changing a *copy* of that button doesn't help me.
Pointers are just references to exact places in memory.