为什么sizeof运算符对数组产生不同的结果
为什么sizeof运算符产生 12 个字节,而它应该只有 4 个?当我引用变量时array,它只引用数组第一个索引的内存地址。事实上,我打印了第一个索引的内存地址&array[0]并将其与 进行了比较array,它们产生了相同的内存地址结果,这证实它们都指的是数组的第一个索引,但是 'array' 产生 12 字节而array[0]产生 4 字节.
int main() {
int array[] = {1,2,3};
int a = 1;
int b = sizeof(array); //this is referring to the first index of the array
int c = sizeof(array[0]); //this is also referring to the first index of the array
std::cout << b << std::endl;
std::cout << array << std::endl; //they have the same memory address
std::cout << &array[0] << std::endl; /* they have the same memory address, which confirms that array
and &array[0] is the same */
return 0;
}
回答
数组和指针不一样,这是一个很好的例子。
在大多数情况下,数组衰减为指向其第一个成员的指针。其中几次这种衰变不会的不会发生的事情是,当阵列是主题sizeof运营商。在这种情况下,它引用整个数组,并且表达式计算为整个数组的大小(以字节为单位)。
这在C 标准的第 6.3.2.1p3 节中有描述:
除了当它是的操作数
sizeof运算符,_Alignof操作者,或theunary&操作者,或是用于初始化一个数组,其具有类型“的阵列的表达字符串文字类型”被转换为与类型“指针到一个表达键入”指向数组对象的初始元素,而不是左值。如果数组对象具有寄存器存储类,则行为未定义。
以及第 7.2 节中的C++11标准:
“NT 数组”或“T 的未知边界数组”类型的左值或右值可以转换为“指向 T 的指针”类型的纯右值。应用了临时物化转换 (7.4)。结果是指向数组第一个元素的指针。
和 8.3.3p4:
左值到右值 (7.1)、数组到指针 (7.2) 和函数到指针 (7.3) 的标准转换不适用于 的操作数
sizeof。如果操作数是纯右值,则应用临时物化转换 (7.4)。
所以我们实际拥有的是:
int b = sizeof(array); // size of the entire array
int c = sizeof(array[0]); // size of the first element of the array
int d = sizeof(&array[0]); // size of a pointer to an array element