Re: Warning when using const pointer to fixed size array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux