Initialization from incompatible pointer type warning when assigning to a pointer

后端 未结 5 530
梦谈多话
梦谈多话 2020-12-06 16:46

GCC gives me an \'Initialization from incompatible pointer type\' warning when I use this code (though the code works fine and does what it\'s supposed to do, which is print

5条回答
  •  一向
    一向 (楼主)
    2020-12-06 17:27

    TL;DR Check the types.

    • &arr is of type int (*) [5] (pointer to an array of 5 ints).
    • arr is of type int [5], but not always.

    Quoting C11, chapter §6.3.2.1, (emphasis mine)

    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.

    hence,

     int *q = arr;   // int[5] decays to int *, == LHS
    

    and

     int *q = &arr[0];   // RHS == LHS
    

    are same, whereas,

     int *q = &arr; // LHS (int *) != RHS (int (*) [5])
    

    is a mismatched type expression.

    Now, it works, because, as already mentioned in Lundin's answer, the address of the array variable is likely to be the same as the address of the first element of the array, so despite the type mismatch, the value is same, so this seems to work.

提交回复
热议问题