Lesson 3 of 6 · Strings, Structs and Files · 2 min read · Updated

Structs: grouping related data

Stop passing six separate variables around. Give the group a name.

A struct groups variables that belong together into one type. A student has a name, a roll number, and marks — those are one thing, not three.

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

struct Student {
    char name[50];
    int  roll;
    float marks;
};

int main(void)
{
    struct Student s;

    strcpy(s.name, "Priya");
    s.roll = 42;
    s.marks = 87.5f;

    printf("%s (%d) scored %.1f\n", s.name, s.roll, s.marks);

    return 0;
}
Output
Priya (42) scored 87.5

An array of structs

c
struct Student class[3] = {
    {"Priya", 1, 87.5f},
    {"Arun",  2, 73.0f},
    {"Meena", 3, 91.5f}
};

for (int i = 0; i < 3; i++) {
    printf("%-8s %.1f\n", class[i].name, class[i].marks);
}

Structs and pointers: the arrow

c
void give_bonus(struct Student *s)
{
    s->marks += 5.0f;        /* arrow: through a pointer */
    /* (*s).marks += 5.0f;      exactly the same thing */
}

Note

Use . when you have the struct itself, and -> when you have a pointer to it. The arrow exists purely because (*s).marks is awkward to type and easy to get wrong.

Note

Passing a large struct by value copies the whole thing. Pass a pointer instead when the struct is big, and add const if the function has no business changing it.

You have struct Student *p;. How do you read the name?

Create a free account to save your progress, or sign in.