Warning when using const pointer to fixed size array

Aaron Rocha hxdg21@yahoo.com
Tue Dec 1 14:54:00 GMT 2009


> 
> 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.
> 

The advantage of declaring a pointer like I had mentioned in my original
posting is that I will get a compiler error if someone tries to give me a
buffer of a different size. Let's say you are only working
with fixed size buffers and you are expecting to get a pointer to one of
them. The prototype of your function could look like this:

void foo(const int * p, int plen);

However, in this case you will have to:

a) Verify that plen matches the fixed size you are expecting

b) Trust that the caller indeed gave you a buffer p with valid plen
   memory locations.

c) Problems will not be caught at compile time. Only at run-time.

This is ok if you are working with buffers that may vary in size. But if
your buffers have a fixed size, wouldn't it be better to do this?

void foo(const int (* p)[9]);

In this case, you are guaranteed that the caller is giving you a valid
buffer. Otherwise, you will get a compile error message which will help
you quickly detect a problem.

Do you understand now the motivation behind the question?

This is the reason why I am trying to do this:

int array[9];
const int (* p)[9] = &array;

But gcc complains that:

"warning: initialization from incompatible pointer type"

And I don't see why. Where in the standard it says that I am not allowed 
to do this? Should I log a bug against gcc so that I can get an explanation
from the developers themselves?

Thanks



      __________________________________________________________________
Make your browsing faster, safer, and easier with the new Internet Explorer® 8. Optimized for Yahoo! Get it Now for Free! at http://downloads.yahoo.com/ca/internetexplorer/



More information about the Gcc-help mailing list