简体   繁体   中英

Why does casting and dereferencing struct pointers lose information?

I have two struct types

typedef struct {
    int i;
    int j;
} struct_a;

typedef struct {
    int i;
} struct_b;

where struct_a and struct_b obviously share a common initial sequence. Based on these structs I have the following snippet in which I convert between struct_a and struct_b by casting and dereferencing pointers

struct_a a = { 0, 1 };
printf("%i %i\n", a.i, a.j);

struct_b b = *((struct_b *)&a);
printf("%i\n", b.i);

struct_a c = *((struct_a *)&b);
printf("%i %i\n", c.i, c.j);

The output of the above code after compiling with gcc is

0 1
0
0 0 <= ?

My question is why does c lose the value of j that was specified when initializing a ? Is it because dereferencing the pointers, for instance, in

struct_b b = *((struct_b *)&a);

effectively copies the struct?

Yes, you are copying. When copying a to b , there is only room for one value. The other one is lost.

And the cast in the last assignment is not allowed, so you could have any result from that.

Casting and dereferencing struct pointers does not lose information.

Some notes about your code:

  • a , b and c are different locations in memory.
  • cj has not been initialized in the code, its value could be anything.

Casting the type back and forth for the same variable produces the expected result:

struct_a c = *((struct_a *)((struct_b *)&a)); 
printf("%i %i\n", c.i, c.j);

Another option that produces the expected result:

struct_a a = { 0, 1 };
printf("%i %i\n", a.i, a.j);

struct_b *b = (struct_b *)&a; // *b points a
printf("%i\n", b->i);

struct_a c = *((struct_a *)b); // c is a copy of a
printf("%i %i\n", c.i, c.j);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM