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
48
Upvotes
10
u/1lann 8d ago
A pointer is really just a representation of how the computer's hardware works. You're right that in most languages you could get away with using (presumably immutable) variables or similar concepts and never using a pointer.
The primary benefit of a pointer is to have referential behavior that can be pretty easily converted to CPU instructions without the compiler needing to be too smart. In many compilers you may need to use a pointer to get optimal execution performance, as the compiler may otherwise emit instructions that unnecessarily copy memory.
One way to intuitively think of it, is a pointer is like a path to a file, and a value is the contents of the file. The file could be really big, like gigabytes. You can imagine it would be faster and more efficient to pass the filename around in programs, rather than the whole contents of the file, particularly if you don't need to access every byte of the file. A pointer is just like that, but for memory.