Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   i[a] & a[i] related.. (http://www.go4expert.com/forums/ia-ai-related-t29312/)

IndiraP 27Nov2012 18:34

i[a] & a[i] related..
 
#include <stdio.h>
main()
{
char a[5] = "abcd";
int b = 3;

printf("%c\n",a[b]);
printf("%c\n",((char *) b)[(int) a]);
}


i get d d as output..
a[3] = d..i get it..

what ((char *)b)[(int) a] doing there...
all i can understand from the above is that it is doing something that is producing lyk i[a] from a[i] type..
wats happening der actually n how is it happening???

xpi0t0s 28Nov2012 03:01

Re: i[a] & a[i] related..
 
It's casting b, which is an integer, to a char*, then casting a, which is an array but taken as a char* in this context, to an integer, then using pointer[offset] syntax to address the 'd'.

pointer[offset] is just worked out as pointer+offset*sizeof(*pointer) so there's no difference between a[b] and b[a], providing b and a in the latter case are cast correctly.

IndiraP 12Dec2012 02:20

Re: i[a] & a[i] related..
 
Thank u..:)


All times are GMT +5.5. The time now is 18:45.