Thursday, May 10, 2012

C++ - Understanding Pointers

Pointers are a shockingly complex yet very simple thing to master in C++. The idea of a pointer is easy for most, yet the implementation can be a bit tricky for some.

Below is a quick example showcasing pointers. Comments are lingual representations of each line.

int x = 10; //Initialize integer x to 10.
int *px=&x; //Point variable px to the memory address (&) of x.

cout << px <<endl;/*Output the value of px, which is the numeral string representing the memory address of x.*/

cout << *px<<endl;/*Output the value of what px is pointing to.*/

int **ppx=&px;/*Initialize pointer ppx to point at the memory address of px, the pointer of x.*/

cout << *ppx<<endl;/*Output the contents of what ppx holds, which is the memory address of x.*/

cout << **ppx<<endl;/*Output the value of what the pointer this pointer points to is pointing at*/

**ppx+=1;/*The chain of pointers as displayed in the comment above happens and assigns variable x to 1. This is the same as *px=1; and x=1;*/

So, as you can see, pointers are a somewhat confusing concept. Your next question may be "Why even use them?" Well, the answer is: you shouldn't. Only use pointers in situations when they are required by the language or for a considerable performance gain, such as function parameters. This is called passing by reference since you give the reference to a variable's memory address rather than the value of the variable itself. This means that functions do not have to work with copies. You can make functions look like they take value rather than reference by doing something like this:

void doStuff(int &param){}  
This passes by reference because of the "&" operator, which returns the memory address of the parameter rather than the parameter itself. Now, the function can be called exactly like it were pass by value, like so:

doStuff(arg);  

 Pointers are not useless. They are extremely useful since you can have multiple pointers pointing to the same variable and even pointers pointing to other pointers. This comes in especially handy with multithreading.

No comments:

Post a Comment