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

标签 c arrays function

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/

相关文章:

c - 在 ShellExecute 函数中将 stderr 和 stdout 获取为字符串

ios - -[__NSCFDictionary objectAtIndex :]:

javascript - 有没有办法使用函数参数的值来声明变量

C 中的堆栈变量损坏

c++ - 在 Ubuntu 中监控键盘按键

C、openMPI : What is the best way to distribute blocks of data from each process to all other processes?

java - 在 libGdx 中用随机 vector 2填充数组

javascript - 如何使用 jQuery 创建具有唯一高度的数组和 div?

javascript - 新 html 元素的旧 javascript 函数

c - MPI 集体操作和进程生命周期 (C/C++)