I read a couple of books and they do not explain quite well about what is the purpose of pointers. Why we use them in a function instead of regular variables?
Here are some examples of situations in which you need pointers:
- you need to allocate memory of which you can't know the size at compile time
- you need to allocate memory too big for the stack
- you need data to be available outside the scope of its allocation
- ( C only ) you need to modify the variable passed as argument to a function
Pointer are - as the name suggests - pointing to some other information. They can point to other variables, to parts inside other variables (e.g. to a specific element in an array variable) or they can point to "nothing" (null-pointer).
Think of a web page. That's your variable (a big html-text). While reading, you come to a nice phrase you want to use in your own web-page (another variable). You could either copy'n'paste the whole phrase, which means copying the whole text. This is what "normal variables" like an int or float or std::string are about: You copy the content to the new variable.
Or you could just link to the web-page or even link into the site (if the author made a good structure of his variable..err..web-page). That's a pointer. Now you also see the great additional advantage (or disadvantage, if you don't like this feature) of a pointer: Should anyone change the original site, you don't have to copy the text again. It's automatically at the newest version (since you only link/point to the page/variable).
You also get a lot of new trouble: If the site you point to is deleted, you get an illegal link. Accessing this link in a browser gives a harmless "404 not found". In C++ that means usually segmention fault and your programm will terminate immediately.
And you have a bit different syntax. Like in the web-world, where you would have to click one additional time for each link to get to the real content, you need to "dereference" each pointer to get to the real value. This is why you need to write *p = 23; instead of just p = 23; (which would set the link to a new web-pag^H^H...variable. ;-) )
Hope it helped.
Ciao, Imi.
PS: If you stumble upon "C++ References": They are more like proxy servers or automatic redirects.. but that's another story :-D