C Structures

A structure lets you group several related variables together under one name, even when they have different types. Instead of juggling separate variables for a person's name, age, and height, you can bundle them into a single struct that travels together as one unit.

Declaring a structure

You define a structure with the struct keyword, followed by a name and a list of members inside curly braces. Each member is just a normal variable declaration. The definition itself does not create any storage; it only describes the shape of the data.

Defining and using a struct

#include <stdio.h>

struct Car {
    char brand[20];
    int year;
    float price;
};

int main() {
    struct Car myCar = {"Toyota", 2022, 25000.0};

    printf("Brand: %s\n", myCar.brand);
    printf("Year: %d\n", myCar.year);
    printf("Price: %.2f\n", myCar.price);
    return 0;
}

Once you have a struct variable, you reach its members with the dot operator. So myCar.year reads the year field, and you can assign to it the same way.

Setting members one at a time

You do not have to fill in everything at declaration time. You can create the struct first and assign values later, member by member. Note that for string members you use strcpy rather than plain assignment.

Assigning members individually

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

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p;
    p.x = 4;
    p.y = 7;

    printf("Point is (%d, %d)\n", p.x, p.y);
    return 0;
}
  • Use the dot operator (.) to access members of a struct variable.
  • Members can be of any type, including arrays and other structs.
  • Copying one struct into another with = copies all its members at once.
  • String members need strcpy, since you cannot assign an array with =
TermMeaning
structKeyword that begins a structure definition
memberA single variable inside the structure
.Operator to access a member of a struct variable
->Operator to access a member through a struct pointer
Note: The semicolon after the closing brace of a struct definition is required. Forgetting it is a very common beginner mistake that produces confusing compiler errors.

Exercise: C Structures

What is the main purpose of a C `struct`?