|
To access the value of a variable through a
pointer, the indirection operator '*' is used. Program 5.1
illustrates how the indirection operator is used.
//Program 5.1
//Pointer manipulation through indirection operator
#include<iostream.h>
void main()
{
int *iPtr, iVar = 10;
iPtr = &iVar; //Initializing the pointer with the address of
iVar
cout<<"Value os iVar is "<<iVar<<endl;
//The following statement also prints the value of iVar but
through a pointer
cout<<"Value of iVar accessed through a pointer is "<<*iPtr<<endl;
}
The output of Program 5.1 is:
Value of iVar is 10
Value of iVar accesed through a pointer is 10
The following program also illustrates pointer manipulation:
//Program 5.2
//Pointer manipulation
#include<iostream.h>
void main()
{
int iVar = 10, *iPtr;
iPtr = &iVar; //Initialize the pointer with the address of
the variable
cout<<"Value of iVar before incrementing is "<<iVar<<endl;
*iPtr += 5; //Incrementing the value of the variable through
a pointer
cout<<"Value of iVar after incrementing is "<<iVar<<endl;
}
The output of Program 5.2 is:
Value of iVar before incrementing is 10
Value of iVar after incrementing is 15
In this program iPtr points to iVar and the value of iVar is
incremented using iPtr. |