The de-reference operator ( * ) is also called
operator. Indirection means accessing the value at the address held by
The pointer provides an indirect way to read the value held at that address.
Pointers can offer a highly efficient means of accessing and changing data.
Since pointers contain the actual address of the data, the compiler does less work when finding that data in memory.
Naming and Initializing Pointers:
Pointers can have any name that is legal for other variables. Many programmers follow the convention of naming all pointers with an initial
p, as in
pCount or pNumber.
|int Count = 10; // declare and initialize a regular int variable
int *pCount = 0; // declare and initialize an integer pointer
All are the same:
int* pCount = 0;
int *pCount = 0;
int * pCount = 0;
All pointers, when they are created, should be initialized to some value, even if it is only zero.
A pointer whose value is zero is called a null pointer.
Practice safe programming:
Initialize your pointers!
If the pointer is initialized to zero, you must specifically assign
the address to the pointer.
pCount = &Count; // assign the address to the pointer (NO *
It is also possible to assign the address at the time of declaration.
int *pCount = &Count; //declare and assign an integer pointer
cout<< Count; //prints
cout<< pCount; // prints 0x8f4dff4, or the current address of
cout<< *pCount; // prints 10
|The * appears before the pointer variable in only TWO places:
1. when you declare a pointer variable, and
2. when you de-reference a pointer variable (point to (access) the data whose address is stored in the pointer)
It is important to distinguish between
· a pointer,
· the address that the pointer holds, and
· the value at the address held by the pointer.
//Example - variable of type pointer
char first = 'A';
char second = 'B';
char *p = &first;
<< endl; // dereference - output A
p = &second;
cout<< *p <<endl;
//dereference - output
*p = 'Z';
// set first to 'Z'
p = &second;
*p = 'Y';
<< first << second <<endl;