Warning when using const pointer to fixed size array
Andrew Haley
aph@redhat.com
Tue Dec 1 09:52:00 GMT 2009
Aaron Rocha wrote:
> I am using :
>
> $ gcc -dumpversion
> 4.2.4
> $ gcc -dumpmachine
> x86_64-linux-gnu
>
> As expected, the following code does not generate any warnings when compiling with -Wall:
>
> int main() {
>
> int number = 0;
>
> const int * const t = &number;
>
> return *t;
> }
>
> However, this code does:
>
> int main() {
>
> int array[9] = {0};
>
> const int (* const p)[9] = &array;
>
> return (*p)[0];
> }
>
> $ gcc -Wall ./tst2.c
> ./tst2.c: In function âmainâ:
> ./tst2.c:7: warning: initialization from incompatible pointer type
>
> In order to eliminate this warning, I have to declare array as:
>
> const int array[9];
>
> Why is this the case though? In both examples, I am trying to use a const pointer to access a non-const variable for read-only purposes. Isn't this supposed to be OK?
You're really tying yourself in knots here. The address of an array
is the address of its first member, so
int main() {
int array[9] = {0};
const int *p = array;
return p[0];
}
Andrew.
More information about the Gcc-help
mailing list