-2

Why sizeof(array_name) is the size of the array and sizeof(&a[0]) is the size of pointer even though, when an array name is passed to a function, what is passed is the location of the beginning of the array.

coco97
  • 65
  • 7
  • 1
    Because that's what the C spec stipulates. An array does not decay to a pointer when passed to `sizeof`, unless you make it so (as in `&a[0]`). – nanofarad Aug 11 '18 at 20:59

2 Answers2

2

In most expressions, when an array is used, it is automatically converted to a pointer to its first element.

There is a special rule for sizeof: When an array is an operand of sizeof, it is not automatically converted to a pointer. Therefore, sizeof array_name gives the size of the array, not the size of a pointer.

This rule also applies to the unary & operator : &array_name is the address of the array, not the address of a pointer.

Also, if an array is a string literal used to initialize an array, it is not converted to a pointer. The string literal is used to initialize the array.

The rule for this is C 2018 6.3.2.1 3:

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. If the array object has register storage class, the behavior is undefined.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Array parameters to functions don't exist. They turn into pointers (the innermost index does, if the array is multidimensional). It's just syntactic sugar inherited from the B language. void f(int *X) == void f(int X[]);

(Same for function params to functions. void g(void X(void)) == void g(void (*X)(void))).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142