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
480 views
in Technique[技术] by (71.8m points)

c - What's the difference between array and &array?

Assume that

int array[16];

There is standard conversion called array-to-pointer conversion, so array would be converted implicitly to type int*, but why &array is equal to array?

For instance,

int array[16];
void *p = array;
void *q = &array;
printf("%p
", p);
printf("%p
", q);

This will give out the same address and no compiling error.

Why?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The type of &array is int (*)[16] (a pointer to an array of 16 integers). The type of array, when left to decay, is int* (a pointer to an integer). They both point to the same location, but have a different meaning to the compiler.

If you do (&array)[0], the value you end up with is the original array of 16 integers, that you can subscript again, like (&array)[0][0]. (&array)[1] would be the next array of 16 integers, if there was one.

If you do array[0], the value you end up with is an integer, which you can't subscript again. array[1] is just the next integer. (This is true regardless of if array is a int[16] or a int*.)

Obviously, if you then turn your pointers into void pointers, you lose any semantic difference there could have been.


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

...