Structures: Your Own Types

Grouping things that belong together

A student has a name, an age and a grade. Keeping them in three separate variables gets messy, especially with many students. A structure (struct) packs them together into one new type:

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

struct Student {
    char name[30];
    int age;
    double grade;
};

int main() {
    struct Student s;
    strcpy(s.name, "Priya");
    s.age = 16;
    s.grade = 8.5;

    printf("%s is %d and has grade %.1f\n", s.name, s.age, s.grade);
    return 0;
}

Output

Priya is 16 and has grade 8.5
  • struct Student { ... }; describes the new type. Each item inside is a field. Don't forget the ; after the }!
  • struct Student s; creates a variable of that type.
  • The dot . reaches a field: s.age means "the age of s".

Think of it like this: A struct is like a form with boxes to fill in: Name ___, Age ___, Grade ___. The struct is the blank form; each variable is one filled-in copy.

Filling it in one go

With a full compiler you can give all the fields at once, in the same order as in the struct:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p = {3, 7};
    printf("(%d, %d)\n", p.x, p.y);
    return 0;
}

Output (on your own computer with gcc – the simple C runner in the browser editor can't run this one)

(3, 7)

Tip: The simple C runner in the browser editor can't do = {3, 7} for structs, so in the challenges fill in each field on its own line: p.x = 3; p.y = 7;

Copying a struct

Unlike arrays, a whole struct can be copied with =:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point a;
    a.x = 1;
    a.y = 2;
    struct Point b = a;   // copies both fields
    b.x = 100;
    printf("a = (%d, %d), b = (%d, %d)\n", a.x, a.y, b.x, b.y);
    return 0;
}

Output

a = (1, 2), b = (100, 2)

Remember: Define the struct once at the top, then create as many variables of that type as you like.

HOME LABS COMMUNITY DASHBOARD