Pages

Monday, June 07, 2010

C




Today we shall discuss about a simple C program.
I would like to explain the difference between array and &array address.
So, let's start by taking a live question. 
Q. Find the o/p:
main()
{
    char *ptr="hello";
    char ary[]="world";

printf("Ans:\n");
printf("PTR: &ptr=%x, ptr=%x, *ptr=%x, ptr[0]=%x\n", &ptr,ptr, *ptr, ptr[0]);
printf("ARY: &ary=%x,ary=%x, *ary=%x, ary[0]=%x\n", &ary, ary, *ary, ary[0]);
}

Ans:
PTR: &ptr=bfb86990, ptr=8048524, *ptr=68, ptr[0]=68
ARY: &ary=bfb8698a,ary=bfb8698a, *ary=77, ary[0]=77

When you look at the output of array and &array you will find that they both are same. Why? But, whereas in the case of a character pointer (not a character array), they seems to differ. Why again?

We all know that an array is like a constant pointer, and the address of the arrary is also indicated by the name of the array itself. Hence, when we mention arrary and when we mention &array they both mean the same and point to the same location. Memory allocation also happens in the same area as the starting address of the array.
But, but in case of a character pointer, prt and &ptr points to two distinct and different locations. &ptr is the place which is used by the compiler itself to store the actual data string that is pointed by ptr. &ptr points to a .rodata area inside the data segment, accessible and allocated by the compiler itself.

That is the only reason, why you get a segmentation fault while trying to modify the data pointed by the ptr character pointer.