gpt4 book ai didi

c++ - 为什么 sizeof 运算符对数组产生不同的结果

转载 作者:行者123 更新时间:2023-12-05 08:47:40 25 4
gpt4 key购买 nike

为什么 sizeof 运算符应该只有 4 个字节,却产生了 12 个字节?当我引用变量 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 standard 的第 6.3.2.1p3 节中有描述。 :

Except when it is the operand of the sizeof operator, the _Alignof operator, or theunary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

以及 C++11 7.2 节中的标准:

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion (7.4) is applied. The result is a pointer to the first element of the array.

和 8.3.3p4:

The lvalue-to-rvalue (7.1), array-to-pointer (7.2), and function-to-pointer (7.3) standard conversions are not applied to the operand of sizeof. If the operand is a prvalue, the temporary materialization conversion (7.4)is applied.

所以我们实际拥有的是:

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

关于c++ - 为什么 sizeof 运算符对数组产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67125273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com