CC · Lesson 6 of 8

Structs

Structs let you group related data together. They're C's version of objects — without the methods, inheritance, or any of the fun parts.

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

// Define a struct type
typedef struct {
    char name[50];
    int age;
    double gpa;
} Student;

// Struct with a pointer to another struct (linked list node)
typedef struct Node {
    int value;
    struct Node *next;  // pointer to same type
} Node;

// Function that takes a struct pointer
void print_student(const Student *s) {
    printf("Name: %s, Age: %d, GPA: %.2f\n", s->name, s->age, s->gpa);
    //                                          ^^^ arrow for pointer access
}

int main() {
    // Initialize a struct
    Student s1 = {"Alice", 20, 3.8};
    Student s2;
    strcpy(s2.name, "Bob");  // use strcpy for string fields
    s2.age = 22;
    s2.gpa = 3.5;

    // Access with . (dot) for values, -> for pointers
    printf("%s is %d years old\n", s1.name, s1.age);

    Student *ptr = &s2;
    printf("Via pointer: %s\n", ptr->name);  // arrow notation

    // Function with pointer argument
    print_student(&s1);
    print_student(&s2);

    // Array of structs
    Student class[3] = {
        {"Charlie", 21, 3.7},
        {"Diana",   19, 3.9},
        {"Eve",     23, 3.6},
    };

    for (int i = 0; i < 3; i++) {
        print_student(&class[i]);
    }

    return 0;
}
◆ Note
typedef struct { ... } Name; is the standard C idiom to avoid writing struct every time. Without it, you'd need to write struct Student everywhere. The typedef just creates an alias.