Initialization from an incompatible pointer type warning when assigned to a pointer

GCC gives me the warning “Initialization from an incompatible pointer” when I use this code (although the code works fine and does what it should do, which prints all the elements of the array).

#include <stdio.h>

int main(void)
{
    int arr[5] = {3, 0, 3, 4, 1};
    int *p = &arr;

    printf("%p\n%p\n\n", p);

    for (int a = 0; a < 5; a++)
        printf("%d ", *(p++));
    printf("\n");
}

However, no warnings appear when I use this bit of code

int main(void)
{
    int arr[5] = {3, 0, 3, 4, 1};
    int *q = arr;

    printf("%p\n%p\n\n", q);

    for (int a = 0; a < 5; a++)
        printf("%d ", *(q++));
    printf("\n");
}

The only difference between the two fragments is that I assign * p = & arr and * q = arr.

  • What distinguishes and what does?
  • And why does the code execute and give the same result in both cases?
+3
source share
5 answers
  • &arr , int(*)[5], .
  • arr, , int *q = arr;, "" . int *q = &arr[0];

int(*)[5] a int*. , .

, int , , . "", .

+5

() ( ), :

int *q = arr;
/* OR */
int *q = &arr[0];

- :

int *q = &arr;
+1

, arr[0] arr[]. , arr[0], arr[0]; , . . , , , .

0

TL; DR .

  • &arr int (*) [5] ( 5 int s).
  • arr int [5], .

C11, §6.3.2.1 ( )

, sizeof, _Alignof & , , , type '' '', lvalue.

,

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

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

,

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

- .

, , Lundin answer, , , , , , , , , , .

0

lvalue . , int *q = arr; int pointer q arr: .

&arr - . ( ) . int ( ), . , , Undefined .

, . , , int *p = arr; p, int *p = arr;. , .

BTW, Undefined , , , , .. ( ; ))

0

All Articles