4. Pointers in C++
Fourth article in the series
Sherman Chin, Wednesday 06 October 2004 - 10:18:25

Although not a feature of OOP alone, pointers are a key feature of the C and C++ language. Today, I will skim through the basics of pointers so that you will be able to follow the rest of our ongoing tutorial.

What is a pointer? You can think of a pointer as a variable that contains the actual computer memory address of another variable. Simply put, integer variables store integers, character variables store characters and pointer variables store memory addresses.

You can get the memory address of a variable by using the &, otherwise known as the address of operator. Once you obtain the memory address, you can then store it in a pointer variable or pointer in short. If a pointer stores the address of a variable, it "points" to the variable, hence the name.

If you ask me, a pointer is kind of like a shortcut in Windows. You know, the icons on your desktop that has a little arrow on them. They are shortcuts to program files but are not actual programs themselves. They contain the locations of the program files so that they can activate them when you click on the shortcut icon. Similarly, pointers contain the address of variables and you can access the variable pointed to via the pointer itself.

Let us take a look at some code where pointers are used:

#include <iostream.h>

void main()
int iValue = 123;
char strName[7] = "Merlin";

int* ptrValue;
char* ptrName;

ptrValue = &iValue;
ptrName = strName;

cout << "The address of iValue is " << ptrValue << endl;

cout << "The contents of the variable pointed to by ptrValue is "
<< *ptrValue 
<< endl;

cout << "The contents of the variable pointed to by ptrName is " 
<< ptrName
<< endl;

The output of the program will be:

The address of iValue is 0x0065FDF4
The contents of the variable pointed to by ptrValue is 123
The contents of the variable pointed to by ptrName is Merlin

Note: The address of iValue will probably be different on your computer depending on where in memory the variable iValue is stored.

The previous source code illustrates some interesting pointer syntax. To declare a pointer that points to certain type of variable, we must append an asterisk to the variable type followed by the pointer name. Just use the syntax: variableType* variableName;
So, to declare a pointer of type integer, we use: int* variableName; Please note that to declare multiple pointers on a single line, we have to precede each variable name with the asterisk to indicate we are declaring pointers, e.g. int* variableName1, * variableName2, * variableName3;

Next, be sure to point the pointer at an integer variable or it will be pointing at some arbitrary location in memory, which will probably cause your system to crash if you use the pointer without initializing it first. We initialize a pointer by pointing it to the address of a variable. In our case, ptrValue = &iValue;

We assign the address (obtained by using the '&' operator), of the variable pointed to, to the pointer, ptrValue. Be sure that the variable type pointed to is the same as the pointer's variable type as declared.

Since ptrValue stores the address of our integer value, iValue, we can print iValue's address simply by typing: cout << "The address of iValue is " << ptrValue << endl;

What if we wanted the value of variable pointed to by our pointer? We have to use the indirection operator, *. Please don't get confused with this * and the * used to declare our pointer. They are completely different. The latter is used to tell our C++ compiler that we are declaring a pointer variable, whereas the former indirection operator is used to indicate that we want to access the value of the variable pointed to by our pointer.

So, to display the contents of the variable pointed to by our pointer, we can type: cout << "The contents of the variable pointed to by ptrValue is " << *ptrValue << endl;

Some of you may be wondering why the char pointer does not work the same way after observing the source code. Here is where most people get confused. Notice that the char variable strName is not a single value but a char array variable. The char array contains 7 values: 'M', 'e', 'r', 'l', 'i', 'n', '\0'.

The seventh character is a null, '\0', character that indicates the end of a string. All character arrays should end with a null character to indicate the end of a string of characters. This is the reason why character arrays have an extra space allocated for an invisible character. C++ uses the null character to identify the end of a string when applying library functions, as you will see later.

Reminder: An array is a way to group together a number of variables of a single data type. The individual variables stored in an array can be accessed using an index number that starts from the element 0 to the (maximum size of the array -1). Thus, our char strName[7] = "Merlin"; defines an array with the maximum size of 7 - index number ranging from 0 to 6. To display the character 'M' in our array, we can type: cout << strName[0] << endl; // The output will be the first element of the array

Also note that we can assign the characters to our character array individually, e.g. char strName[7] = {'M', 'e', 'r', 'l', 'i', 'n', '\0'};

To simplify assigning a string to a character array, C++ allows us to use the shortcut: char strName[7] = "Merlin";

Both statements have the same meaning.

An array functions in much the same way as a pointer does. It points to starting address location in the computer's memory of which the array starts off. The index number in brackets can be thought as the offset to access each element of the array e.g. we can access the last (seventh) element of our strName array by typing: cout << strName[6] << endl; Remember the offset begins at index number 0.

The output of the program is:

Hello! I am a character.
My name is Adam.
Hello! I am a character.
My name is Merlin.
I am a wizard as well.
I can cast spells.
Hello! I am a character.
My name is Connan.

We have made some minor modifications to the program to use a character pointer:

void setName(char* ptrName)
strcpy(strName, ptrName);

In our new setName function, we are passing a character pointer as an argument to its parameter list. So far, we have been using the void type as an argument in all our functions' parameter lists.

This time we need to pass an argument to the setName function to initalize our strName character array variable. Notice that we need only declare our ptrName in our parameter list, as it is local to the setName function and will not be used outside of the function.

By including the string.h header file, we can use the strcpy library function. This function is used to copy the characters from our character pointer to our character array. Its syntax is strcpy(destinationVariable, sourceVariable); The reason why we cannot assign ptrName to strName directly by using the assignment operator, =, is because strName is an array of characters.

In our program, we first invoke the setName function with the constant name of our character as its argument from "main" e.g. adam.setName("Adam"); The constant string "Adam" is passed to the function where it is pointed to by the pointer ptrName. Next, we copy the value pointed to by ptrName to strName. In our example, strName will contain the value "Adam". We can then display the value of strName by typing: cout << "My name is " << strName << "." << endl;

That is all for today's tutorial. I know it has been a pretty difficult tutorial but please take the time to key in the source code in this tutorial, compile and run them. You should also try modifying the program by changing values and experimenting by yourself. This will help you further understand the program and help you to learn via trial and error.

this content item is from Sherman3D
( http://www.sherman3d.com/S3Dplugins/content/content.php?content.5 )