This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Warning when using const pointer to fixed size array


Aaron Rocha wrote:
>> 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];
>> }

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

Yes, and gcc is right.  The type of the array is array[9] of int,
whereas the type of your pointer is pointer to array[9] of const int.

> And I don't see why. Where in the standard it says that I am not
> allowed to do this?

6.7.3 Para 8: "If the specification of an array type includes any type
qualifiers, the element type is so qualified, not the array type.  For
two qualified types to be compatible, both shall have the identically
qualified version of a compatible type."

> Should I log a bug against gcc so that I can get an explanation
> from the developers themselves?

I am one.

Andrew.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]