C Structures and Unions
Short answer: a struct groups several variables of different types under one name, so related data travels together. A union also groups members, but all of them share the same memory, so it holds only one value at a time. Structs model records; unions save memory or reinterpret data.
Defining and using a struct
#include <stdio.h>
#include <string.h>
struct Student {
char name[30];
int age;
float grade;
};
int main(void) {
struct Student s1 = {"Asha", 20, 88.5f};
s1.age = 21; // dot operator for members
struct Student s2;
strcpy(s2.name, "Ravi");
s2.age = 22;
s2.grade = 91.0f;
printf("%s is %d\n", s1.name, s1.age);
return 0;
}
Arrays inside structs cannot be assigned with =; copy text with strcpy or snprintf. See arrays and strings.
typedef: shorter names
typedef struct {
int x;
int y;
} Point;
Point p = {3, 4};
printf("%d,%d\n", p.x, p.y);
typedef lets you write Point instead of struct Point.
Designated initializers
Point origin = { .x = 0, .y = 0 };
struct Student t = { .name = "Meera", .grade = 79.0f }; // other members become zero
Pointers to structs
void birthday(struct Student *s) {
s->age += 1; // arrow operator: same as (*s).age
}
birthday(&s1);
Passing a pointer avoids copying the whole struct and lets the function change the original. Use const struct Student * for read-only access. Pointers are explained in pointers in C.
Nested structs and arrays of structs
typedef struct {
char street[40];
char city[20];
} Address;
typedef struct {
char name[30];
Address home; // nested struct
} Employee;
Employee team[3]; // array of structs
strcpy(team[0].name, "Asha");
strcpy(team[0].home.city, "Pune");
Dynamic structs and linked lists
typedef struct Node {
int value;
struct Node *next; // pointer to the same type
} Node;
Node *node = malloc(sizeof *node);
node->value = 10;
node->next = NULL;
A struct can hold a pointer to its own type, which is how linked lists and trees are built. Free every node; see memory management.
Memory layout and padding
struct A { char c; int i; char d; }; // often 12 bytes
struct B { int i; char c; char d; }; // often 8 bytes
The compiler inserts padding bytes so members are aligned to their natural boundaries. Ordering members from largest to smallest usually shrinks the struct. Use sizeof(struct A) to check, and never assume a struct has no padding when writing it to a file or network.
Unions
union Value {
int i;
float f;
char text[8];
};
union Value v;
v.i = 42;
printf("%d\n", v.i);
v.f = 3.14f; // overwrites the same memory
printf("%f\n", v.f);
The size of a union equals its largest member. Only the most recently written member is valid to read (reading another is implementation-defined or unsafe in some cases).
Tagged unions
typedef enum { INT_T, FLOAT_T } Kind;
typedef struct {
Kind kind;
union { int i; float f; } data;
} Number;
Number n = { .kind = INT_T, .data.i = 7 };
if (n.kind == INT_T) printf("%d\n", n.data.i);
Pair a union with a tag that records which member is active. This is the C version of a "variant" type.
Enums
enum Color { RED, GREEN, BLUE }; // 0, 1, 2
enum Color c = GREEN;
Struct vs union
| struct | union | |
|---|---|---|
| Memory | Sum of members (plus padding) | Size of the largest member |
| Members valid | All at once | One at a time |
| Use for | Records, objects, nodes | Variant data, hardware registers, saving memory |
Common mistakes
- Using
.on a pointer instead of->. - Comparing two structs with
==(not allowed); compare member by member. - Forgetting to initialize pointer members.
- Assuming struct sizes are the sum of members.
For the language overview, read what C is.
FAQs
Can a struct contain a function?
Not directly, but it can hold function pointers, which is how C emulates methods.
Can I copy a struct with =?
Yes, assignment copies all members, including arrays inside. Pointer members are copied as addresses, not the data they point to.
Why use typedef?
It shortens declarations and hides whether a type is a struct, which improves readability.
When is a union useful?
For memory-constrained data, parsing binary formats and variant types with a tag.
