array 和 &array 有什么区别? [英] What's the difference between array and &array?

查看:63
本文介绍了array 和 &array 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

int array[16];

有一个标准的转换叫做数组到指针的转换,所以array会被隐式转换成类型int*,但是为什么&array 等于 array?

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?

例如

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

这将给出相同的地址并且没有编译错误.

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

为什么?

推荐答案

&array 的类型是 int (*)[16](指向16 个整数的数组).array 的类型,当任其衰减时,是 int*(指向整数的指针).它们都指向相同的位置,但对编译器的意义不同.

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.

如果你做(&array)[0],你最终得到的值是16个整数的原始数组,你可以再次下标,比如(&array)[0][0].(&array)[1] 将是下一个由 16 个整数组成的数组,如果有的话.

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.

如果你做array[0],你最终得到的值是一个整数,你不能再次下标.array[1] 只是下一个整数.(无论 arrayint[16] 还是 int*,都是如此.)

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*.)

显然,如果您随后将指针转换为 void 指针,您将失去可能存在的任何语义差异.

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

这篇关于array 和 &array 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆