Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - Why do "a+1" and "&a+1" give different results when "a" is an int array?

int main()
{
    int a[]={1,2,3,4,5,6,7,8,9,0};

    printf("a = %u , &a = %u
",a,&a);
    printf("a+1 = %u , &a+1 = %u
",a+1,&a+1);
}

how a and &a are internally interpreted?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Both statements print out addresses and are probably meant to explain pointer arithmetic.

a and &a are NOT the same, they have different types, but hold the same memory address.

&a is of type int (*)[10] (which acts like a pointer to an array)
a is of type int [10] (which acts like a pointer to a single element)

So when you add 1 keep those types in mind. The pointer will be offset by the size of the type that the address contains. a+1 offsets by the size of int, i.e. to the second element in the array. &a+1 offsets completely past the whole array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...