Skip to content
C

Structs

Group related fields with typedef and pass by pointer for mutation.

By EZ4Code Team
structtypedef

Code

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

typedef struct {
    char  name[32];
    int   age;
    float gpa;
} Student;

// Pass by pointer to avoid copying and allow mutation
void birthday(Student *s) {
    s->age++;
}

void print_student(const Student *s) {
    printf("%-10s age=%d gpa=%.2f\n", s->name, s->age, s->gpa);
}

int main(void) {
    Student a;
    strncpy(a.name, "Alice", sizeof(a.name) - 1);
    a.name[sizeof(a.name) - 1] = '\0';
    a.age = 20;
    a.gpa = 3.7f;

    Student b = {"Bob", 22, 3.5f};

    print_student(&a);
    birthday(&a);
    print_student(&a);
    print_student(&b);
    return 0;
}

Explanation

A struct groups related fields of different types into one named unit, and typedef gives that type a short alias. The arrow operator -> accesses fields through a pointer, while the dot operator accesses them directly. Passing structs by pointer avoids copying large values and lets functions modify the caller's data.

More C Snippets