作为参数传递的数组的sizeof的怪异行为 [英] Weird behavior of sizeof for arrays passed as parameters

查看:82
本文介绍了作为参数传递的数组的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?

}

类似的函数参数被视为sizeof的简单指针. 但是为什么会这样呢?它在任何地方都有记录吗?

Looks like function parameters are treated as simple pointers for sizeof. But WHY does this happen? Is it documented anywhere?

推荐答案

在C ++中我从未见过这种语法,但也许你是想

I never saw that syntax before in C++ but maybe you meant

void foo(const char data[10])

无论如何,在C ++数组中,当传递给函数时,它们会衰减到指针.因此,该函数无法知道传递的数组有多大.从这个意义上讲,我上面写的完全等同于:

Anyway, in C++ arrays decay to pointers when passed to a function. So the function has no way of knowing how big the passed arrays are. In that sense, what I wrote above is completely equivalent to:

void foo(const char data[])

与此主题有关的还有 C常见问题解答.

这篇关于作为参数传递的数组的sizeof的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆