Paragraph 6.7.3.8 of the C99 spec states
If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array ty
This is a known issue that has been discussed several times over the last 10 years at comp.std.c. The bottom line is that the specific case you presented is not currently legal in Standard C; you need to either remove the qualifier or refrain from using a pointer to an array to refer to the qualified elements in the array.
If you think you have a good idea to overcome the issue, you can post it to news:comp.std.c
for discussion. If others agree that it is a good idea, you or someone else can file a defect report to have the behavior changed (there are several committee members that frequent comp.std.c so feedback from the people who would potentially be reviewing the DR would be useful to have prior to filing it). I think there may be some issues with your proposal to have qualifiers affect the array itself, but I'd have to give it some more thought.
Possible workaround for the C programmer (but not the compiler designer):
gcc with -Wcast-qual
does not complain about this:
void g(const double *ap, int n)
{
int i;
struct box
{
double a[n];
};
const struct box *s = (const struct box *)ap;
for (i=0; i<n; ++i)
{
doStuffWith(s->a[i]);
/* ... */
}
}
Even if it's not very elegant. The trailing array member a
also has a slightly different meaning between C89 and C99, but at least you get the intended effect.
The situation is awkward with pointers (ie, arrays), but here's my recollection of the details:
const double *ap
is a pointer to a constant double;
double *const ap
is a constant pointer to a double;
const double *const ap
is a constant pointer to a constant double;
So I believe it is possible to do what you're asking, although I've not tried this in years -- the gcc
option you're using wasn't available the last time I did this!
EDIT: This answer is not correct for the question - I'm leaving it to preserve the comments below, which clarify the problem for mere mortals (or rusty C developers...)