Lesson 6 of 12

Structs

Learn to group related data into structs, which C uses where other languages would use objects.

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;
}
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.