Lesson 91 +10 XP

Structures (struct)

Structures (struct)

A struct bundles several related values under one name. Think of it as a custom data type you design.

The classic example: a person

struct Person {
    char name[50];
    int age;
    float height;
};

This defines a blueprint called Person with three fields.

Creating a struct variable

struct Person person1;

Accessing fields with the dot

strcpy(person1.name, "Ada");
person1.age = 36;
person1.height = 1.7;

Reading a field

printf("%s is %d years old\n", person1.name, person1.age);

Initializing at declaration

struct Person p2 = {"Grace", 85, 1.6};

TL;DR

  • A struct groups related fields into one type.
  • Define with struct Name { fields };.
  • Access members with the dot operator: p.age.
  • Initialize with braces: {"name", age, height}.