作为参数传递的数组的sizeof的奇怪行为

Vie*_*urs 1 c++ parameters sizeof

你能解释一下这个:

void foo(const char data[10])
{
   char copy[10];
   const char copy1[10] = {};

   printf("%i", sizeof(copy)); //prints 10, as expected
   printf("%i", sizeof(copy1)); //prints 10, as expected
   printf("%i", sizeof(data)); //prints 4, WTF?

}
Run Code Online (Sandbox Code Playgroud)

看起来函数参数被视为sizeof的简单指针.但为什么会发生这种情况?是否记录在任何地方?

Pau*_*nta 5

当您将数组传递给函数时,您实际在做的是将指针传递给数组的第一个元素(您可能知道这一点).即使你有一个声明为的参数char[10],这仍然意味着你只得到一个指针,因为C被设计得非常快,所以它避免了复制可能非常大的数据,如数组.在[10]除了可能作为一个提醒程序员也是没有用处的.