y
是一个有 10 个成员的整数数组(大小=40 字节),但是当我将它传递给 my_function()
时如x
, x
有 10 个成员,但如果我尝试获取它的大小 ( sizeof(x)
),我将得到 8 个字节的结果。
您能解释一下为什么会发生这种情况吗?
void my_function(int x[]) {
printf("%d\n", sizeof(x)/sizeof(x[0]));
}
int main() {
int y[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("%d\n", sizeof(y)/sizeof(y[0])); // Output : 10
my_function(y); // Output : 2
return 0;
}
最佳答案
当作为函数参数传递时,数组会衰减为指针,因此在 my_function
语句中 printf("%d\n", sizeof(x)/sizeof(x[0])) ;
等价于 printf("%d\n", sizeof(int*)/sizeof(int));
。在您的计算机和编译器上,指针的大小等于 int 大小的两倍。
关于c - C 中传递给函数之前和之后 sizeof(array) 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311111/