Pointer
POINTER
Consider the declaration,
Int i=3;
This declaration tell the C
compiler to:
·
Reserve space in
memory to hold the integer value.
·
Associate the
name i with this memory location.
·
Store the value 3
at this location.
We can print this address number
through following program:
#include<stdio.h> int main() { int i=3; printf("Address of i = %u\n",&i); printf("Value of i = %d\n",i); printf(“Value of i = %d\n”,*(&i)); return 0; }
Output will:
Address of i = 2686748
Value of i = 3
Value of i = 3_
Hence it is printed out using
%u which is a format specifier for
printing an unsigned integer.
Note printing the value of *(&i) is same as printing the value
of i.
The expression &i gives
the address of the variable i. This address can be collected in a variable, by
saying,
j=&i
But remember that j is not an ordinary variable like any
other integer variable. It is a variable that contains the address of another
variable (i in this case ).
i Contains
the value 3 whose address is 2686748 and
j’s value is i’s address i.e.
2686748.
Let see a program for better
clearance…..
#include<stdio.h> int main() { int i=3; int *j; j=&i; printf("Address of i = %u\n",&i); printf("Address of i = %u\n",j); printf("Address of j = %u\n",&j); printf("Value of j = %d\n",j); printf("Value of i = %d\n",i); printf("Value of i = %d\n",*(&i)); printf("Value of i = %d\n",j); return 0; }
Output
Address of i = 2686748
Address of i = 2686748
Address of j = 2686744
Value of j = 2686748
Value of i = 3
Value of i = 3
Value of i = 3
_
Carefully observe the above
program for better understanding.
Here is another program
showing you how to use pointer in
function call
#include<stdio.h> int swap(int *,int *); int main() { int a=10,b=20; swap(&a,&b); printf("a = %d b = %d\n",a,b); return 0; } int swap(int *x,int *y) { int t; t=*x; *x=*y; *y=t; }
Output
a =20 b = 10
_
No comments