gpt4 book ai didi

c - C 中传递给函数之前和之后 sizeof(array) 之间的差异

转载 作者:行者123 更新时间:2023-11-30 16:12:33 25 4
gpt4 key购买 nike

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/

25 4 0
文章推荐: javascript - 如何从
中获取数据并在单独的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com