4.5. pointers.cpp

Time: 00:13:45 | Download: Large Small | Streaming
Review

The three characteristics of a variable, Figure 3(b).

pointers.cpp demonstrates pointers and pointer operators. The program does not solve a real problem, so providing test cases is not feasible. This example introduces the basic pointer operators and concepts without explaining why we use them. The program also introduces two new manipulators. hex displays the value appearing at its right in hexadecimal (i.e., base 16), while dec displays the value appearing at its right in decimal (i.e., base 10).

Previously, the asterisk, *, was used as the multiplication operator. In this example, the asterisk takes on two new roles, and the compiler must distinguish which of the three possible operations it represents by the context in which it appears. When * has a number on each side, it represents multiplication. As part of a variable definition, * denotes a pointer variable (i.e., a variable capable of storing an address). Finally, when used with a single pointer variable, * represents the dereference operator (also known as the indirection operator).

#include <iostream>
using namespace std;

int main()
{
	int     i = 10;			// (a)
	int*	p = &i;			// (b)

	cout << i << endl;		// (c)
	cout << hex << &i << endl;	// (d)
	cout << hex << p << endl;	// (e)
	cout << dec << *p << endl;	// (f)
	cout << hex << &p << endl;	// (g)

	return 0;
}
pointers.cpp. The program demonstrates pointers and pointer operators but does not solve a real problem. The example introduces the basic pointer operators and concepts without explaining why we use them.
  1. Defines variable i and initializes it to 10 (i.e., stores 10 at the address represented by the variable named i).
  2. Defines p as a pointer variable, specifically, a pointer to an integer. In this statement, the variable i appears on the right side of the assignment operator, where it normally represents the contents of i. However, the address of operator, &, returns the address of variable i (i.e., where i is stored in memory). A pointer is an address, so it is legal to store the address of i in the pointer variable p.
  3. Prints the contents of variable i which is 10, to the console.
  4. Prints the address of i (which can change each time the program runs) to the console in hexadecimal.
  5. Prints the contents of p (which is the address of i) to the console in hexadecimal.
  6. The dereference operator or indirection operator accesses the contents of variable i indirectly through the pointer variable p This operation is a way of accessing the contents of a variable without using its name and is the most difficult pointer operation to understand.
  7. Prints the address of p to the console. Note that, like all variables, p has an address; furthermore, like all pointers, it also stores or contains an address.