Re: organization of struct elements in the memory.



On Mar 8, 8:45 pm, "santosh" <santosh....@xxxxxxxxx> wrote:
aiooua wrote:
hello,

Is the following code proper?

-----
typedef int one_data;
typedef long two_data;
typedef struct one_{
char *name;
one_data info;
}one;
typedef struct two_{
char *name;
two_data info1; // not the same as one_data.
}two;

typedef union{
one o;
two t;
}composite;

int main(){
composite c;
c.o.name="a";
printf("%s\n",c.t.name); // can i access the common prefix field?
}
---

In other words, I'm assuming that if instances of two structs start at
the same memory location, then all the common starting elements can be
accessed using either handle. Is this assumption valid across all
compilers/platforms?

If they're within the same union, then yes, otherwise, the standard
doesn't guarantee it. However, for any one platform, it'll usually
work, with a pointer cast.

thanks for the replies. they were useful.

.



Relevant Pages