为什么衰减到指针数组参数出现不适为sizeof()? [英] Why does decay to pointer for array argument appear not to apply to sizeof()?

查看:153
本文介绍了为什么衰减到指针数组参数出现不适为sizeof()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我由于被这样的一个完全相同的副本读了前面的问题已关闭

I read a question earlier that was closed due to being an exact duplicate of this

的sizeof数组作为参数传递

<一个href=\"http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array\">How找到的sizeof(指针指向一个数组)

但看完这个我仍然是如何的sizeof()的作品混淆。据我所知,传递一个数组作为参数传递给一个函数,如

but after reading this I am still confused by how sizeof() works. I understand that passing an array as an argument to a function such as

  void foo(int a[5])

将导致数组参数衰减的指针。我没有在上面2问题的链接找到的是一个明确的答案,为什么它是在的sizeof()函数本身是(或至少从看似豁免豁免)这个指针衰减行为。如果的sizeof()的表现就像任何其他的功能,那么

will result in the array argument decaying to a pointer. What I did not find in the above 2 question links was a clear answer as to why it is that the sizeof() function itself is exempt from (or at least seemingly exempt from) this pointer decay behaviour. If sizeof() behaved like any other function then

   int a[5] = {1,2,3,4,5};
   cout << sizeof(a) << endl;

那么上面应该输出 4 而不是 20 。我错过了一些东西很明显,因为这似乎是衰减到指针行为的一个矛盾?对不起,再次提出这个问题,但我真的有理解为什么出现这种情况,尽管有愉快地使用该函数多年没有真正思考它很难。

then the above should output 4 instead of 20. Have I missed something obvious as this seems to be a contradiction of the decay to pointer behaviour??? Sorry for bringing this up again but I really am having a hard time of understanding why this happens despite having happily used the function for years without really thinking about it.

推荐答案

由于标准是这样说的(重点煤矿):

Because the standard says so (emphasis mine):

(C99,6.3.2.1p3)除了当它是sizeof操作符或一元和放大器的操作;操作员或用来初始化数组文本字符串,当然$有Type类型的数组p $ pssion转换为前pression与指向数组对象的初始元素,不是左值的类型指针输入。

(C99, 6.3.2.1p3) "Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue."

请注意,对于C ++,标准中明确表示,大小是数组的大小:

Note that for C++, the standard explicitly says the size is the size of the array:

(C ++ 11,5.3.3p2 sizeof的)[...]当应用于阵列,其结果是在阵列中的总字节数。这意味着,n的阵列的大小
  元素是一个元素的大小n次。

(C++11, 5.3.3p2 sizeof) "[...] When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element."

这篇关于为什么衰减到指针数组参数出现不适为sizeof()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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