GCC issues an incompatible pointer type warning

When I compile the program below using GCC 4.9.2, I get the following warning: pass argument 1 from 'P from an incompatible pointer type. However, I do not see anything wrong with the program. Any clues?

typedef int Row[10];

void P(const Row A[])
{
}


int main(void)
{
    Row A[10];

    P(A);
    return 0;
}

Here is the full GCC output on stderr:

test.c: In function β€˜main’:
test.c:12:4: warning: passing argument 1 of β€˜P’ from incompatible pointer type
  P(A);
    ^
test.c:3:6: note: expected β€˜const int (*)[10]’ but argument is of type β€˜int (*)[10]’
 void P(const Row A[])
      ^

Edit: The program compiles using Clang 3.5.0 and options -pedantic -std=c89 -Wall.

+4
source share
2 answers

Get rid of typedef and it will become a little clearer:

void P (const int A [][10])
{
}

int main(void)
{
    int A[10][10];

    P(A);
    return 0;
}

The problem is that the array in the function parameter "decays" into a type pointer const int(*) [10], which is a pointer to the array where the elements are const.

, main, int(*)[10].

"pointer-to-type" "- ". , int*, const int*, . .

"pointer-to-array" "const-pointer-to-array", "--const-", , .

, C: const . - :

P( (const int(*)[10]) A);

, .


: C11 , , , :

#define const_array_cast(arr, n) _Generic(arr, int(*)[n] : (const int(*)[n])arr )

void P (const int A [][10])
{
}


int main(void)
{
    int A[10][10];

    P(const_array_cast(A,10));
    return 0;
}
+5

.

typedef int Row[10];

void P(const Row A[])
{
}


int main(void)
{
    const Row A[10];

    P(A);
    return 0;
}
-1

Source: https://habr.com/ru/post/1663936/


All Articles