Search code examples
carrayssizeofmingw32

sizeof operator on array name when offset is added


I was curious about sizeof(arrayName + offset). It gives me the sizeof(pointer). Though array name is actually a constant pointer in C, sizeof(arrayName) gives the size in bytes of an array. So I guess the compiler treat (arrayName+offset) as pure pointer even for sizeof() and hence only exception while using the array name would be sizeof(arrayName).

Is this behavior sizeof(arrayName + offset) well defined by the compiler? I am using MinGW 32 bit compiler. Also is there any way we can know the size of partial array other than by using simple math like (sizeof(arrayName) - offset*sizeof(arrayName[0]))?

Is sizeof(arrayName) is not an inconsistent language construct in C/C++? For all other purpose, arrayName is treated as an address. And when we pass array to a function, this behavior may lead to bugs and beginners always have issue with this.


Solution

  • An array name is converted to a pointer to its first element in all but three cases:

    • The operand of the address-of operator &
    • The operand of the sizeof operator.
    • The operand of the _Alignof operator.

    This is detailed in section 6.3.2.1 of the C standard:

    3 Except when it is the operand of the sizeof operator, the _Alignof 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.

    In the case of sizeof(arrayName + offset), the operand of sizeof is the expression arrayName + offset. The type of this expression is a pointer type, since arrayName is converted to a pointer in order to perform pointer arithmetic with offset. So the sizeof expression evaluates to the size of a pointer.

    In the case of sizeof(arrayName), the operand of sizeof is an array, so it evaluated to the size of the array in bytes.

    Both of these behaviors are well defined by the C standard.