Difference Between Structure and Union in C (With Memory Layout)
In low-level memory modeling, knowing the difference between structure and union layouts is critical for hardware registers and network packet parsers. The difference between the two structures: structure and union in C is that structure stores all the elements in different memory location sequentially (along with the alignment padding) and union stores all the elements in a same memory location in which the largest sized member can be stored. Writing to one union member overwrites the shared bytes, so unions are perfect for type-safe tagged variants and for protocols which have to be kept in memory-constrained embedded systems.
Difference Between Structure and Union in C: sizeof, Padding & Shared Memory — Technical Overview
In low-level memory modeling, knowing the difference between structure and union layouts is critical for hardware registers and network packet parsers. The difference between the two structures: structure and union in C is that structure stores all the elements in different memory location sequentially (along with the alignment padding) and union stores all the elements in a same memory location in which the largest sized member can be stored. Writing to one union member overwrites the shared bytes, so unions are perfect for type-safe tagged variants and for protocols which have to be kept in memory-constrained embedded systems.
#include <stdio.h>
struct PacketStruct {
int id;
double payload;
};
union PacketUnion {
int id;
double payload;
};
int main(void) {
printf("sizeof(struct PacketStruct) = %zu bytes\n", sizeof(struct PacketStruct));
printf("sizeof(union PacketUnion) = %zu bytes\n", sizeof(union PacketUnion));
return 0;
}
Runnable C example
#include <stdio.h>
struct PacketStruct {
int id;
double payload;
};
union PacketUnion {
int id;
double payload;
};
int main(void) {
printf("sizeof(struct PacketStruct) = %zu bytes\n", sizeof(struct PacketStruct));
printf("sizeof(union PacketUnion) = %zu bytes\n", sizeof(union PacketUnion));
return 0;
}Expected Output
sizeof(struct PacketStruct) = 16 bytes
sizeof(union PacketUnion) = 8 bytes