Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decay to pointer for array argument appear not to apply to sizeof()?

Tags:

c++

c

pointers

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

When a function has a specific-size array parameter, why is it replaced with a pointer?

and

How to find the 'sizeof' (a pointer pointing to an array)?

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])

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;

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.

like image 445
mathematician1975 Avatar asked Jul 01 '12 15:07

mathematician1975


People also ask

What does it mean to decay an array to a pointer?

The loss of type and dimensions of an array is known as array decay. It occurs when we pass the array into a function by pointer or value. First address is sent to the array which is a pointer. That is why, the size of array is not the original one.

Does sizeof work on arrays?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.


1 Answers

Because the standard says so (emphasis mine):

(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."

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

(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."

like image 179
ouah Avatar answered Sep 28 '22 03:09

ouah