Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

c - Initialization from incompatible pointer type warning when assigning to a pointer

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 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
%p

", p);

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

However no warning is given when I use this bit of code

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

    printf("%p
%p

", q);

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

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

  • Exactly what different is the & making ?
  • And why does the code execute and give the exact same output in both the cases ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • &arr gives an array pointer, a special pointer type int(*)[5] which points at the array as whole.
  • arr, when written in an expression such a int *q = arr;, "decays" into a pointer to the first element. Completely equivalent to int *q = &arr[0];

In the first case you try to assign a int(*)[5] to a int*. These are incompatible pointer types, hence the compiler diagnostic message.

As it turns out, the array pointer and the int pointer to the first element will very likely have the same representation and the same address internally. This is why the first example "works" even though it is not correct C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...