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.