数组与& array [0]之间的区别 [英] Difference between array and &array[0]
问题描述
int array[] = {1,2,3,4};
据我了解,array
只是指向&array[0]
但是,为什么sizeof(array);
知道数组的大小,而不仅仅是知道它只有4个字节的数字?
But how come then sizeof(array);
knows size of an array and not just that it's only 4 byte number?
推荐答案
除非它是sizeof
或一元&
运算符的操作数,或者是用于在声明中初始化另一个数组的字符串文字,类型为"T
的N个元素的数组"的表达式将被转换(衰变")为类型为指向T
的指针"的表达式,该表达式的值为数组第一个元素的地址.
Except when it is the operand of the sizeof
or unary &
operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" will be converted ("decay") to an expression of type "pointer to T
, and the value of the expression will be the address of the first element of the array.
C中的数组不存储任何有关其大小的元数据或其他任何内容,也不为任何类型的指针留出任何存储空间.它们的布局大致如下:
Arrays in C don't store any metadata about their size or anything else, nor is any storage set aside for any sort of pointer. They're laid out pretty much as follows:
+---+
arr: | 1 | arr[0]
+---+
| 2 | arr[1]
+---+
| 3 | arr[2]
+---+
| 4 | arr[3]
+---+
除了数组元素本身之外,没有单独的变量arr
存储.如您所见,arr
的地址和arr[0]
的地址是相同的.这就是为什么即使类型,表达式arr
,&arr
和&arr[0]
都为您提供相同的 value (第一个元素的地址)的原因这些表达方式是不同的.
There's no separate storage for a variable arr
apart from the array elements themselves. As you can see, the address of arr
and the address of arr[0]
are the same. This is why the expressions arr
, &arr
, and &arr[0]
all give you the same value (the address of the first element), even though the types of those expressions are different.
除非操作数是可变长度数组,否则sizeof
的结果是在编译时计算的,在这种情况下,编译器会将数组操作数视为数组.否则,它将数组表达式视为指向第一个元素的指针.
Except when the operand is a variable-length array, the result of sizeof
is computed at compile time, and the compiler treats array operands as arrays in those circumstances; otherwise, it treats the array expression as a pointer to the first element.
这篇关于数组与& array [0]之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!