Search Menu

Pointers and Basic Structures in C++



Pointers, page 2

page 1 of 2

A pointer is a variable that represents a location in memory; since every variable that you declare has a space in memory, pointers can "point" to the location of any variable. You can find a variable's memory location with the & operator, which returns a variable's address (a constant):

int some_var = 3;
cout << &some_var;	// print out the address of the variable some_var

The output will be a hexadecimal number that will look something like "0x9e145450." You can create a pointer variable to store this location:

int* pointer_var;		// a pointer to an integer
pointer_var = &some_var;	// assign the address location to the pointer

You can then access both the address of some_var, and the value of some_var using the pointer_var variable:

cout << pointer_var << endl;	// prints out the address of some_var,
				// to which pointer_var is now pointing

cout << *pointer_var;		// prints out the value of some_var, 
				// which was defined to be 3 above.

The variable name preceded by an asterisk evaluates to the stored value, whereas the variable name alone evaluates to an address. It is important to recognize the difference between the value of a variable and the variable's location in memory, so it may be worthwhile to reread the above paragraphs; pointers are often considered one of the most difficult aspects of programming to learn. A review of pointer basics can be found here.

Passing by reference

Pointers are often passed to functions. This is called "passing by reference." When you simply pass a variable instead of a pointer to it, you are "passing by value." For instance, the following will not work as the programmer might intend because the variable is passed by value:

void triple(int value){
	value *= 3;	// The value is only changed inside the function

When the function finishes, the program forgets what it did to value. This is because the function created an entirely new variable for value, which goes out of scope when the function returns. You must instead pass by reference by adding a & to the end of the argument data type: