Pointers

Feb 29, 2016 at 6:48am
Why does one use pointers instead of adjusting the value that is stored in the variable directly? I've seen plenty of information regarding how to use them, but they never really answered why.

Feb 29, 2016 at 10:15am
Lots of variables don't have names. Just a memory address. A pointer is the only way to use those variables.
Feb 29, 2016 at 11:34am
See my post in this thread:

http://cplusplus.com/forum/general/105593/

for some reasons to use pointers.

Note that, in modern C++, we tend not to use raw pointers, as we have better tools to achieve these things.
Feb 29, 2016 at 12:50pm
Thanks for the responses. Your list of reasons to use pointers does help me understand a bit better.

I have another question along the same topic. Whats the benefit of using multiple pointers to point to the same pointee?
Feb 29, 2016 at 1:05pm
Whats the benefit of using multiple pointers to point to the same pointee?


It allows one to write programs more complicated than "Hello world".
Feb 29, 2016 at 1:47pm
Trivially, sometimes you might want to have one persistent pointer to something, e.g. the start of an array, and another temporary pointer that initially points to the same place, but then moves along the array.

Also, multiple objects may want access to the same other object, so each one would hold a pointer to that other object.
Feb 29, 2016 at 4:58pm
Well one big advantage of storing the address of an existing variable is that you can pass a pointer to the variable for efficiency instead of passing the variable by value. Like for example if you have a vector of string objects (thousands upon thousands of string objects in that vector) and you want to display the elements of that vector, it wouldn't be a very good idea to just plug in the name of the vector in the calling function as an argument and send it by value as it would get copied and that would result in a performance hit.

There are also many good uses for pointers and MikeyBoy covered some of them in that link.
Mar 1, 2016 at 2:02am
Thank you both for replying and providing information. After seeing both of your responses, I feel I have a better general idea of when and why to use pointers and that is exactly what I was wanting to achieve. I'll leave this post open for a few days to make sure I don't have any more questions before I mark it as Solved. Thanks again!
Mar 1, 2016 at 10:48am
You're welcome - glad it helped!
Topic archived. No new replies allowed.