Online How to use Pointers in C++ Programming with Code sample Example
POINTERSPointer variable is a special variable that contains a memory address. This address is generally of a second variable. Therefore we say that the pointer variable points to the second variable. Pointers can be declared as follows:
int * ptr2int; // ptr2int is a pointer to an integer variable
char * ptr2ch; // ptr2ch is a pointer to an character variable
The address operator & is used to assign a variable's address to a pointer. The dereferencing operator * can then be used to deference a pointer to yield the variable to which the pointer points to. Following example illustrates the use of these operators.
int var = 3 ;
int * ptr ;
ptr= & var ;
cout<< " *ptr is "..*ptr ;
cout<<"\n Enter a value : " ;
cout<<" var is "<<var ;
How Does This All Happen?Now a few words about the actual changes going in the memory. When the first statement is executed, a memory location is allocated for the integer variable var and 3 is stored in the location. After the second statement is executed, another memory location is reserved for the pointer variable ptr. After the third statement the address of the first location is put in the second one. Finally when the user inputs the value for *ptr, the value is written in the first memory location whose label is var.
ptr var Address=24657 Address=12345 Graphically we use the following notation ptr var