Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

arrays - Why does i[arr] work as well as arr[i] in C with larger data types?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C, pointer arithmetic is defined so that writing

ptr + k

does not advance the pointer by k bytes, but by k objects. Thus if you have a pointer to an integer array and writing

*(myIntArrayPointer + 3)

You are dereferencing a pointer to the element at index 3 in the array, not the integer that starts three bytes past the start of the object.

Similarly, if you subtract two pointers, you get the logical number of elements in-between them, not the total number of bytes. Thus writing

(myIntArrayPointer + 3) - myIntArrayPointer

yields the value 3, even though there are 3 * sizeof(int) bytes in-between them.

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...