When should I use a pointer instead of a regular variable?
Asked by
MellowOrbit42
I've completed a beginner programming course, but I still don't have a strong understanding of why things work. In a recent review problem, the solution used a pointer, and I'm confused about why it points to a variable's memory address instead of simply using the variable itself. I've watched several tutorials, but pointers still seem equivalent to ordinary variables to me. What practical problems do pointers solve, and when should I use one?
Answers
The biggest difference is copying versus referring to the original data. Passing a normal value to a function usually gives the function its own copy. Passing a pointer gives it an address, so it can work with the same memory as the caller. That matters when the function needs to modify the original variable or when copying the value would be expensive.
Reply to this answer
Pointers expose how memory is represented underneath the language. Theyโre needed in C when manually managing memory or working with heap allocations, and theyโre useful when an object may not exist yet or when data is arranged in separate places in memory. They arenโt automatically better, thoughโif a copy is small and you donโt want shared mutable state, passing a value or returning a modified copy can be clearer and safer.
Reply to this answer
Pointers are also useful for dynamically allocated data, large objects, and data structures such as linked lists, trees, stacks, and queues. Instead of moving the whole object around, you can pass a small address that refers to it. They also let multiple parts of a program share one object.
Reply to this answer
A simple way to think about it is that a variable is the contents of a house, while a pointer is the houseโs address. In C, x means the value stored in x, &x means the address of x, and *p means the value found at the address stored in p. If a function receives a pointer to x and writes through it, the original x changes; if it receives x by value, only a temporary copy changes.
Reply to this answer
Add your answer
Answers are reviewed before publication.
QuietHarbor8: For example, a sorting function should usually operate on the callerโs array rather than create and sort a separate copy of the entire array.