Вопрос

Are struct well defined in strict c 89? I mean this code

struct a {
    int a, b;
    void * c;
} k;
//init k...
struct b {
    int u, w;
    long *data;
} p = *(struct b*)&k;

is going to work on every compiler that support the standard? If I reverse the cast (e.g. cast from struct b to struct a) c is going to be the same as the beginning? I'm pretty sure it works with gcc(even with -ansi -pedantic), microsoft compiler and so on, but does it guarantee that it is standard c 89?

Thank you!

Это было полезно?

Решение

Don't do this. Copy the fields manually:

struct b p;

p.u = k.a;
p.w = k.b;
p.data = (long *) k.c;

Your code would most likely run just fine since long * and void * will typically be identically implemented, but why risk it? The standard says stuff like:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

Note the last sentence, where pointers to "other types" (such as long) are made distinct from pointers to void.

The above is explicit, safe, and much clearer.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top