In article <44************@individual.net>,
Christian Kandeler <ch****************@hob.de> wrote:
Michael Mair wrote:
Christian Kandeler wrote: I'd like to know whether the following code is standard-compliant:
struct generic {
int x;
int a[1];
};
void f(struct generic *s)
{
int i;
for (i = 0; i < 10; i++)
s->a[i] = i;
}
int main(void)
{
struct special {
int x;
int a[10];
} s;
f((struct generic *) &s);
return 0;
}
No, it is not. Do you want a C99 or C89 answer?
Essentially, offsetof(struct generic, a) needs not
be equal to offsetof(struct special, a)...
Okay. But if I use a flexible array:
struct generic {
int x;
int a[];
}
is the offset the same, then? I'm not sure if I can deduce that from the
standard. If it is, does that make the rest of the code legal?
With a flexible array, the offset if a is the same as the offset in
_some_ variant of the struct with fixed array size. Lets say the
compiler chooses one offset when the array size is < 10 and another one
if array size is >= 10, and no other offset, then the offset in the
flexible struct is one of those two offsets. But you don't know which
one.
The other difference is that with any fixed size array, the compiler can
assume that the index is within the bounds. If you use a fixed size
array of size 1, then the compiler can legally ignore the index you pass
and always access array element 0, because that is the only one that you
could access legally. With the flexible size array, the compiler must
produce code that works no matter how large the array is. So here you
have an improvement.