Why sizeof(array) and sizeof(&array[0]) gives different results?

前端 未结 8 992
悲&欢浪女
悲&欢浪女 2020-12-30 06:56
#include 
int main(void){
    char array[20];

    printf( \"\\nSize of array is %d\\n\", sizeof(array) );  //outputs 20
    printf(\"\\nSize of &         


        
8条回答
  •  悲&欢浪女
    2020-12-30 07:36

    In the expression sizeof array, array is not converted to a pointer type.

    C11, § 6.3.2.1 Lvalues, arrays, and function designators

    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.

    Therefore, its type is char[20], not char *. The size of this type is sizeof(char) * 20 = 20 bytes.

    C11, § 6.5.3.4 The sizeof and _Alignof operators

    The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.

    &array[0] type is char *. That's why the sizeof(&array[0]) gives the same result as sizeof(char *) (4 bytes on your machine).

提交回复
热议问题