struct/union pointer/address stuff.

K

Kenneth Bull

Say,

struct foo
{
int x;
double y;
/* etc. more variables defined */
short u;
char z;
} a;


Are the following true on all systems?

1) &a == &a.x
2) (&a.x < &a.y) && ( .. etc.. ) && ( &a.u < & a.z)


Are the following true if we change 'struct' to union above, on all
systems?

3) &a == &a.x
4) &a.? == &a.? where ?s can be x, y, ..., u, or z (not necessarily
equal for both ?s)


Thank you for the help.
 
C

Chris Torek

Kenneth Bull said:
struct foo
{
int x;
double y;
/* etc. more variables defined */
short u;
char z;
} a;


Are the following true on all systems?

1) &a == &a.x

"Sort of". The problem here is that &a and &a.x have different
*types*. This is a bit like asking whether 3 and 3.0 are "the
same":

#include <stdio.h>
int main(void) {
if (3 == 3.0) puts("3 and 3.0 are identical");
if (sizeof 3 != sizeof 3.0) puts("3 and 3.0 are different");
return 0;
}

This program, run on most of my machines, says that 3 and 3.0 are
both identical *and* different (because they compare equal, but
"sizeof 3" is 4, and "sizeof 3.0" is 8).

If you convert &a and &a.x to some common (and thus comparable)
type, they will be equal, provided of course the conversion is
valid in the first place. For instance:

assert ((void *)&a == (void *)&a.x);

will never fail.

(Contrast this with, for instance:

if ((char)3 == (char)3.1415) puts("3 and 3.1415 are identical");

which claims that they are identical. After converting to one
common type, they are equal, but if we chose a different type --
such as "float" or "double" -- they would compare unequal. The
Standard says that, for the first element of the "struct", we can
choose *any* suitable type -- such as "struct foo *" or "void *"
-- and the results of the conversion will compare equal.)
2) (&a.x < &a.y) && ( .. etc.. ) && ( &a.u < & a.z)

Again, these have type mismatches. If we convert them to suitable
comparable types, though, this does in fact hold in Standard C.
(It does not hold in some extended versions of C, including GNUC,
where a "zero sized array" may occupy no space.)
Are the following true if we change 'struct' to union above, on all
systems?

3) &a == &a.x
4) &a.? == &a.? where ?s can be x, y, ..., u, or z (not necessarily
equal for both ?s)

Yet again, we have the type mismatch problem, but if we convert all
the addresses to either "void *" or "union foo *", they will indeed
all compare equal.
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top