organization of struct elements in the memory.

A

aiooua

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?
 
R

Richard Bos

aiooua said:
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?

Yes, but...
}

In other words, I'm assuming that if instances of two structs start at
the same memory location,

....only if they're members of the same union, which is the only way this
assumption can reasonably (i.e., without reprobate pointer hackery) hold
true.
It would be a very unusual implementation indeed which did not allow
this kind of aliasing even when the two structs are _not_ members of the
same union, but the Standard does not guarantee that.

Richard
 
S

santosh

aiooua said:
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.
 
A

aiooua

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top