When should I use a pointer instead of a regular variable?

0
9
Asked By MellowOrbit42 On

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?

4 Answers

Answered By BrightKite29 On

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.

Answered By VelvetMaple63 On

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.

Answered By SilverNoodle54 On

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.

Answered By CedarFox17 On

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.

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.