Re: struct compatibility



Christian Kandeler wrote:
Hi,

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

BTW:
struct special {
struct generic access_me;
int a[10 - ((sizeof (struct generic) - offsetof(struct generic, a))/sizeof (int))];
} s;
(with <stddef.h> included) gives you essentially the struct hack,
so you have no "additional badness" related to other struct layout.
The struct hack, even though not covered by the standard, works
presumably on all known implementations.


Cheers
 Michael
--
E-Mail: Mine is an   /at/ gmx /dot/ de   address.
.



Relevant Pages