Structures in C (struct and typedef)

Structures in C — conceptual cover illustration
Structures in C — conceptual cover illustration

Structures (struct) in C create composite user-defined types. Learn struct member access (dot vs arrow operator), memory alignment padding, and struct pointers.

A struct in C is a composite user-defined data type that groups variables of differing types together into a single cohesive memory unit. Structs are used to model real-world entities, records, and packet headers.

Struct members are accessed using the dot operator (student.age) on direct struct variables, or using the arrow operator (ptr->age) when accessing members through a struct pointer.

To optimize memory access speeds on modern hardware, compilers automatically insert alignment padding between struct members. Structs can also be passed by pointer to functions to eliminate large memory copying overhead.

Interactive Runnable C Implementation

#include <stdio.h>
#include <string.h>

// Typedef struct definition
typedef struct {
    int id;
    char name[32];
    float gpa;
    int credits;
} Student;

// Function taking pointer to struct (arrow operator ->)
void print_student(const Student *s) {
    printf("ID: %-4d | Name: %-15s | GPA: %.2f | Credits: %d\n",
           s->id, s->name, s->gpa, s->credits);
}

// Mutate struct via pointer
void update_gpa(Student *s, float new_gpa) {
    s->gpa = new_gpa;
}

int main(void) {
    // Array of structs
    Student roster[] = {
        {101, "Alice Chen", 3.92f, 48},
        {102, "Bob Smith", 3.65f, 32},
        {103, "Charlie Davis", 3.88f, 60}
    };
    int total = sizeof(roster) / sizeof(roster[0]);

    printf("--- Engineering Class Roster ---\n");
    for (int i = 0; i < total; i++) {
        print_student(&roster[i]);
    }

    printf("\n--- Updating Bob's GPA via Pointer (Arrow ->) ---\n");
    update_gpa(&roster[1], 3.82f);
    print_student(&roster[1]);

    return 0;
}

Open example in compiler

Expected Output

--- Engineering Class Roster ---
ID: 101  | Name: Alice Chen      | GPA: 3.92 | Credits: 48
ID: 102  | Name: Bob Smith       | GPA: 3.65 | Credits: 32
ID: 103  | Name: Charlie Davis   | GPA: 3.88 | Credits: 60

--- Updating Bob's GPA via Pointer (Arrow ->) ---
ID: 102  | Name: Bob Smith       | GPA: 3.82 | Credits: 32

Frequently Asked Questions

What is struct memory padding in C?

Processors read memory more efficiently when data types align to multiples of their size (e.g. 4-byte ints at 4-byte boundaries). Compilers add unseen padding bytes between members to meet these alignment constraints.

Related examples