C Intermediate
User-Defined Types: Structs & Unions
Structures and unions allow you to bundle variables of different data types together under a single custom type name.
1. Structures (struct)
In a structure, every member is allocated its own unique location in memory. All members can hold values simultaneously.
#include <stdio.h>
#include <string.h>
struct Product {
char name[30];
int id;
double price;
};
int main() {
struct Product p1;
strcpy(p1.name, "Notebook");
p1.id = 4501;
p1.price = 2.99;
printf("Item: %s (ID: %d), Price: $%.2lf\n", p1.name, p1.id, p1.price);
return 0;
}
2. Pointer to Structs (-> operator)
When accessing struct members through a pointer, use the arrow operator (->) as a shorthand for dereferencing and accessing:
struct Product *ptr = &p1;
ptr->price = 3.49; // Equivalent to (*ptr).price = 3.49
3. Memory Padding & Alignment
The size of a struct is not always the sum of its member sizes. Compilers add invisible bytes (padding) to align member variables to CPU word boundaries for faster access:
struct Sample {
char c; // 1 byte
// 3 bytes of padding inserted here
int i; // 4 bytes
}; // sizeof(Sample) evaluates to 8 bytes, not 5!
4. Unions
Unlike structures, all members in a union share the same memory space. The size of a union is equal to the size of its largest member:
union Measurement {
int meters;
float precision_value;
}; // Shares 4 bytes of memory. Writing to 'meters' overwrites 'precision_value'.