A Pointer Is a Variable That Is Used to Store a Memory Address (Of Variable, Array, Function

Total Page:16

File Type:pdf, Size:1020Kb

A Pointer Is a Variable That Is Used to Store a Memory Address (Of Variable, Array, Function

Pointer

A pointer is a variable that is used to store a memory address (of variable, array, function, class object etc.).

Recall that we use memory bins to store any type of data. And the size of the bin (in terms of bits or bytes) depend on the type of data. When we declare a variable of a particular type (say double length), it reserves a memory bin of that type and assigns the variable name to that bin. A memory bin has an address and is usually expressed in hexadecimal. We can store the address of a memory bin (i.e. of a variable name) in a pointer. Then we can access that bin by the pointer as well as by the variable name.

num reserves a memory bin of type int int num; and assign its name as num 0012FF7C

Address of the memeory bin

Declaring a pointer

long* pnumber; //declares pnumber of type pointer to long long *pnumber; int *pa, *pb; double *pmark;

Note : The asterisk may be attached to either type name or variable name.

int* pnumber, number; //declare pnumber as pointer to int and number as int

Indirection operator *

When we put * immediately before a pointer, it refers to the contents of the memory bin pointed to by the pointer variable. Thus if px is a pointer then *px (in statements other then declaration) means the value stored in the address referred to by px. Note : By now it can be noticed that the same symbol * has different meaning. It is used as multiplication operator, as indirection operator and also to declare a pointer. The compiler is able to distinguish the meaning by the context. The address of operator &

The address-of operator ‘&’ is a unary operator that obtains the address of a variable in the memory. int *pnumber; pnumber=&number; //&number means the address of number and it is stored in pnumber. // Program - P41 y #include x using namespace std; 0012AA14 00FFAB1A void main( ){ int x, y; px int *px; py int *py; x x=10; 10 px=&x; 0012AA14 px py=&y; 00FFAB1A py y=*px; cout<<" x ="<>n; cout<<" Input the numbers\n "; for(int i=0; i>number[i];} for(i=0; i>m; cout<<" No. of columns (max 10)? "; cin>>n; cout<<" Input the elements of the matrix (row wise)\n "; int i,j; for(i=0; i>value[i][j]; } for(i=0; i>n; cout<<" Input the numbers\n "; for(int i=0; i>number[i];} for(i=0; i>n; double *number= new double[n]; double sum=0.0; cout<<" Input the numbers\n "; for(int i=0; i>*(number+i);} for(i=0; i Load more

Recommended publications