C programing Help

I was playing with array and pointers and somehow managed this thing. Can you explain why does this happen.

Code:
main()
{
char p[]="testing";
int i=0;
printf("%c",i[p]);
}
i[p] prints t

but shouldn't we be using p ??
 
you can use p also.

in this case variable p is of char datatype, if you are going to print p, its first place in index[0] is going to get printed always. this is the way char datatype behaves in C;)
 
You are indeed right, though I had never noticed it before :)

I suppose it works out because of the way arrays in C work. The array variable is a pointer to the memory location of the first array member, and the index is the number of positions to skip to get to the element. Now if you use i as the array variable, it is typecast and becomes a pointer to memory address 0. t was the pointer to the start of the array in memory, and when it is typecast as an integer, it becomes a numerical value equal to the number of bytes between the memory address of t and the memory address of the first content in the memory.

If you expand i[p] into *(i + p) it becomes easier to understand.
 
Back
Top