Thursday, September 8, 2011

The difference between pointer to array and pointer to its first element

In the previous Post,We have seen that the address of array and the address of its first element is same,so,the question was what is the difference between Pointer to array and the Pointer to the first element of array while both contains the same address as proved in this Post....
That is if write something like this--
int (*ptr)[5];
ptr=&a;
and a pointer to first element of the array that is....
int *ptr1;

ptr1=a;
Then,What's the Difference between ptr and ptr1??????

To Get the difference between we have just to recall the concept of pointer arithmetic that is what happens if we add some number to a pointer??...
As we know whenever we add any number to the pointer the pointer appends to the memory location which is equal to the sizeof datatype*number....
For example:if a pointer is pointing to an int and its value is 65588 then if we add 1 to the pointer then it goes to 65590 that is (sizeof int *num) that is 2*1=2,so 2 gets added to the pointer and now it points to 65590 memory location...

So,Having the concept of pointer arithmetic in mind when we declare a pointer to an array and increments it the value of the pointer get incremented by sizeof array*datatype size*number...

For example:
if we write int a[5]={1,2,3,4,5};
the sizrof array is 5,
datatype size is 2 for int(16-bit assumed),
and number is 1,
int(*ptr)[5];
ptr=&a;
ptr=ptr+1;or ptr++;
if in address of array is 65516 that is ptr is 65516 in the beginning then after ptr=ptr+1 or ptr++;
The value of ptr is 65516+(5*2*1)=65516+10=65526
This is what happens if ptr is the pointer to array and if the ptr is the pointer to the first elements of the array then as the first element is an int so when we increments the ptr the value get incremented by sizeof int that is it points to the next element...
let us write a program 
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={1,2,3,4,5};
int(*ptr1)[5];
int *ptr2;
ptr1=&a;//pointer to an array
ptr2=&a[0];//pointer to first element of array
printf("The address of array is:%u",ptr1);
printf("\nThe address of first element of array is:%u",ptr2);
ptr1++;
printf("\nNow the value of ptr1 is:%u",ptr1);
ptr2++;
printf("\nNow the value of ptr2 is:%u"",ptr2);
}
output:
The address of array is:65516
The address of first element of array is:65516
Now the value of ptr1 is:65526
Now the value of ptr2 is:65518


I explained to the best of my knowledge,Correct me if there is anything wrong by commenting ,your comments,query and suggestions are invited to raise the level of this blog......
Have a nice time.....