1

I'm learning c and try to understand how c handles the memory space.

When I read the topics about struct and union, I learned that struct do some kind of lining in memory to save space and union put the elements in the same memory location.

I tried code like:

typedef struct {
   double a;
   char b;
} number;

when I try to find the size of the struct, it shows 16 bytes, if I changed the type of a to int, size will be 8 bytes. So I'm a bit confused because the addition of char byte seems to increase the size of struct differently.

Another question is about the union, I did something like:

typedef struct{
    double a;
    union{
        int b;
        double c;
        long d;
    };
} number;

and I set all the fields to the MAX of its type.

In my understanding, union is like a "shared memory", but this test somehow violates this definition.

It turns out that size of this entire struct is 16 bytes, where should the numbers be stored if I set them all to the max, where should the extra bits go. I'm confused.

maple
  • 5
  • 3
  • 1
    structs are padded to meet alignment requirements. – Christian Gibbons Sep 06 '18 at 18:46
  • In the `union` `b`, `c` and `d` all use the same memory, so only one can be used at a time. For example, if you set `d` to 22, then you should ***not*** expect `b` or `c` to have any sensible value. And then later, if you set `c` to 33.3333, then the value in `d` won't be 22 anymore, and you should not expect it to be anything useful. Only one member of a union can be used at any time. – user3386109 Sep 06 '18 at 18:51
  • @Barmar I asked is that an exact duplicate? OP asked `typedef struct { double a; char b; } s1;` is size `16` but `typedef struct { int a; char b; } s2;` is size `8`. But when I saw this [recent answer](https://stackoverflow.com/a/52210515/) to another question I deleted the comment. – Weather Vane Sep 06 '18 at 19:11
  • @WeatherVane People rarely ask the exact same questions as each other. As long as they're similar enough that the answers apply, they can be used as duplicates. – Barmar Sep 06 '18 at 19:15

0 Answers0