Master C structs, unions, and typedef. Learn member access operators, pointer arrow syntax, nested structs, and memory alignment padding.
What is a Structure (struct) in C?
A structure (struct) is a user-defined composite data type that groups variables of different types under a single named entity. Unlike arrays (which hold elements of the same type), structures represent complex domain records such as students, coordinates, or database rows.
Declaring and Using Structs
c (ISO Standard)#include <stdio.h> #include <string.h> struct Student { int id; char name[50]; float gpa; }; int main() { struct Student s1; s1.id = 101; strcpy(s1.name, "Alice Johnson"); s1.gpa = 3.85f; printf("Student ID: %d\n", s1.id); printf("Name: %s\n", s1.name); printf("GPA: %.2f\n", s1.gpa); return 0; }
Using typedef for Cleaner Declarations
The typedef keyword creates an alias for structured types, avoiding the repeated use of the struct keyword:
c (ISO Standard)#include <stdio.h> typedef struct { int x; int y; } Point; int main() { Point p1 = {15, 30}; printf("Point Coordinates: (%d, %d)\n", p1.x, p1.y); return 0; }
Struct Pointers and Arrow Operator (->)
When accessing structure fields via a pointer, use the arrow operator (ptr->member), which is shorthand for (*ptr).member:
c (ISO Standard)#include <stdio.h> typedef struct { int width; int height; } Rectangle; void printRectangle(const Rectangle *rect) { int area = rect->width * rect->height; printf("Rectangle [%d x %d] | Area: %d\n", rect->width, rect->height, area); } int main() { Rectangle box = {10, 20}; printRectangle(&box); return 0; }
Structs vs. Unions
struct: Allocates distinct memory for every member. Total size is at least the sum of all members (plus padding).union: All members share the exact same memory location. The size of the union equals the size of its largest member.
Related Tutorials
- Learn how to persist structs to disk in File Handling in C.
- Review memory addresses and dereferencing in Pointers in C Guide.
- Master homogeneous collections in Arrays in C Programming.