It's fairly common knowledge that if you access an element of an array as arr[i]
in C that you can also access the element as i[arr]
, because these just boil down to *(arr + i)
and addition is commutative. My question is why this works for data types larger than char
, because sizeof(char)
is 1, and to me this should advance the pointer by just one char.
Perhaps this example makes it clearer:
#include <string.h>
#include <stdio.h>
struct large { char data[1024]; };
int main( int argc, char * argv[] )
{
struct large arr[4];
memset( arr, 0, sizeof( arr ) );
printf( "%lu
", sizeof( arr ) ); // prints 4096
strcpy( arr[0].data, "should not be accessed (and is not)" );
strcpy( arr[1].data, "Hello world!" );
printf( "%s, %s, %s
", arr[1].data, 1[arr].data, (*(arr+1)).data );
// prints Hello world!, Hello world!, Hello world!
// I expected `hold not be accessed (and is not)' for #3 at least
return 0;
}
So why does adding one to the array pointer advance it by sizeof( struct large )
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…