How to Find Size of Union in C: Simple Guide
In C, you find the size of a
union using the sizeof operator, which returns the total bytes the union occupies in memory. This size equals the largest member's size, possibly rounded up for alignment.Syntax
The syntax to find the size of a union is simple. Use the sizeof operator followed by the union type or variable name.
sizeof(union UnionName)- size of the union typesizeof(unionVariable)- size of a union variable
This returns the number of bytes the union occupies in memory.
c
sizeof(union UnionName); sizeof(unionVariable);
Example
This example shows how to define a union and find its size using sizeof. It prints the size in bytes, which is the size of the largest member.
c
#include <stdio.h>
union Data {
int i;
double d;
char c;
};
int main() {
union Data data;
printf("Size of union Data: %zu bytes\n", sizeof(data));
return 0;
}Output
Size of union Data: 8 bytes
Common Pitfalls
Common mistakes when finding union size include:
- Confusing union size with sum of all members' sizes. The size is the largest member's size, not the total.
- Ignoring padding and alignment, which can increase the size.
- Using
sizeofon a pointer to union instead of the union itself, which returns pointer size.
c
#include <stdio.h>
union Example {
char a[5];
int b;
};
int main() {
union Example ex;
printf("Wrong size (pointer): %zu\n", sizeof(&ex)); // size of pointer, not union
printf("Correct size (union): %zu\n", sizeof(ex));
return 0;
}Output
Wrong size (pointer): 8
Correct size (union): 8
Quick Reference
- sizeof(unionType): Get size of union type.
- sizeof(unionVariable): Get size of union variable.
- Union size equals largest member size plus padding.
- Do not sum member sizes.
- Use
sizeofon union, not pointer.
Key Takeaways
Use sizeof operator on the union type or variable to get its size in bytes.
Union size equals the size of its largest member, not the sum of all members.
Padding and alignment can affect the union size.
Avoid using sizeof on a pointer to the union; it returns pointer size, not union size.
Always check the size with sizeof to understand memory usage of unions.