Sunday, October 4, 2009

Pointers - Example 1

Program displays elements of the array in reverse order using pointers.Array has 5 elements. If p is the pointer to the first element in the array, then p+4 is the pointer to the last element in the array.The address of the last element is 16 bytes more than the address of the first element. But p is declared an integer pointer so adding 4 to the pointer advances it by 16 bytes in memory(pointer arithmetic).

Note: The stdio.h must be enclosed in between "<" and ">".

#include stdio.h
void main(){
int a[5] = {1,2,3,4,5};
int *p;
p = a ; //or p = &a[0]

printf("%x\n",p);
p=p+4; // the 4 is for the last index
//now p points to the address of the last element in the array

for(int i = 4; i>=0;i--) {
printf ("%d\n", *p); //print a[4]
p--;
}
}

No comments:

Post a Comment