为什么sizeof(array)在这两种情况下不同? [英] Why is sizeof(array) different in these two cases?
问题描述
我目前的系统(似乎是64位给定的指针大小)打印:
Given the following code, the system I'm currently on (which seems to be 64-bit given the size of a pointer) prints:
32
4
现在,此系统上的int大小应为4字节,因此8 * 4 = 32有意义。另外,我理解指针的大小也应该是4个字节,这是我猜测是发生在foo中的数组。
Now, the size of an int should be 4 bytes on this system, so 8*4 = 32 makes sense. Also, I understand that the size of a pointer should also be 4 bytes, which is what I'm guessing is happening to the array in foo.
我的问题是为什么是sizeof(arr)在foo函数中处理不同于sizeof(myarray)在main()当两个都是专门int [8]数组?我预计在这两种情况下都会收到32,它会让我为什么会以其他方式结束。
My question is why is sizeof(arr) in the foo function treated differently than sizeof(myarray) in main() when both are specifically int[8] arrays? I had anticipated receiving 32 in both cases and it confuses me why it would end up otherwise.
#include <iostream>
void foo(int arr[8])
{
std::cerr << sizeof(arr) << std::endl;
}
int main()
{
int myarray[8];
std::cerr << sizeof(myarray) << std::endl
foo(myarray);
}
推荐答案
数组在传递时衰减成指针到函数中,以便在 foo()
中打印4个字节的int数组指针 sizeof
。
Arrays decay into pointers when passed into functions such that you are printing the sizeof
the array pointer of int of 4 bytes in foo()
.
sizeof(myarray)
输出数组的大小为32(num元素x int大小) 。
The sizeof(myarray)
prints the size of the array which is 32 (num elements x size of int).
这篇关于为什么sizeof(array)在这两种情况下不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!