Understanding Pointers in C++

Pointers have the fame of being hard to understand. However, this is not true. Pointers are simple to comprehend. What makes them confusing is how powerful and flexible they can be.

Imagine your computer's entire memory as a long row of containers; where each container has a unique address and can store a value.

A pointer is just container that has a unique address but instead of storing a value it stores the address of a variable. For example, the image below shows the address of the variable myChar stored inside the container myPointer.

The key point is this: A variable stores a value. A Pointer stores the Address of the variable.

Defining a Pointer

A Declaration announces a variable or function to the compiler so that it knows the data type before it compiles it. A Definition is a declaration that reserves storage.

So in the following code:

int main(){

char myChar='b'; //define variable myChar

return 0;
}

The variable myChar is being declared and defined. That is, memory space has been reserved for the variable, and it contains the value: 'b.'

To define a pointer, you specify the data type your pointer will be holding the address of and include the asterik symbol "*" before the pointer's name.

For example:

int main(){

char myChar='b'; //1. define variable myChar

char *myPointer;  //2. pointer definition

return 0;
}

Assigning an address to a pointer

To assign the address of a variable to a pointer, you use the "&" symbol as shown in line 3 below. In C++, the symbol "&" means "the address of."

int main(){

char myChar='b'; //1. define variable myChar

char *myPointer;  //2. pointer definition

myPointer=&myChar; //3. assigning the address of myChar to the pointer myPointer

return 0;
}

If you were to print the value of "myPointer" you will get the address of the variable "myChar."

Dereferencing a Pointer

You can retrieve the value a pointer points to by dereferencing it.

Let's go through a quick example:

int main(){

char myChar='b'; //1. define variable myChar

char myOtherChar; //2. define a variable myOtherChar

char *myPointer;  //3. pointer definition

myPointer=&myChar; //4. assigning the address of myChar to the pointer myPointer

myOtherChar=*myPointer;  //5. dereferencing myPointer

//myOtherChar now holds the value 'b'

return 0;
}

In line 5, we dereference the pointer using the dereferencing operator "*".

In other words, we accessed what the pointer points to, i.e., "myChar" and assigned the value of "myChar" to the variable "myOtherChar."

The dereferencing operator "*" is the same asterisk used to declared a pointer. However, its behavior differs depending on the position of the asterisk in a program. When the asterisk is not used in a declaration, it means "access what the pointer points to." I know this is confusing, but that is how it works in C++.

Hope this helps

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.