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

为什么 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

https://stackoverflow.com/questions/67125273/

相关文章:

css - 在sass中混合两种颜色

python - 避免嵌套 .apply()

macos - MacOS M1 上的 Docker kafka 问题停留在配置上

r - 在 R 中的特定值之后将每行的值设置为 NA

scala - 在范围内显示时未找到隐式

design-patterns - 使用字符串与枚举作为工厂方法的参数?

string - 为什么 String::from(&str) 和 &str.to_string()

r - data.frame 中所有变量对的元素乘法总和

javascript - jQuery 获取所有 值的数组

awk - 拆分但保留分隔符很少