【发布时间】:2021-04-16 12:30:24
【问题描述】:
为什么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(array); //this is referring to the first index of the array你为什么这么认为?array是数组的名称。数组大小是其元素数量乘以元素大小。 -
array->int[3]。array[0]->int -
如果
foo是一个函数,那么表达式foo(array)中的array衰减为指向其第一个元素的指针。但是sizeof(array)不是函数调用。您可以使用成语sizeof array提醒自己这一事实。省略括号时,将sizeof与函数调用混淆起来要困难得多。 -
在大多数上下文中,数组的名称衰减为指向其第一个元素的指针。
sizeof是例外之一;array指的是整个数组,它有3个int类型的元素。 -
@RenzCarillo 阅读:stackoverflow.com/questions/1461432/…