Course contentsShow
← C
Lesson 624 of 1,2199. Structures and UnionsFree lesson

Accessing members of nested structs

Accessing members of nested structs

What you'll learn: How to use the "dot operator" multiple times to drill down into structures defined inside other structures.

The Russian Doll approach

Think of a nested structure like a set of Russian nesting dolls. To get to the smallest doll in the center, you have to open the outer one first, then the next one, and so on. In C, we do this by chaining the dot operator (.).

If you have a Car struct, and inside that Car is an Engine struct, and inside that Engine is a FuelPump struct, you can’t jump straight to the pump. You have to follow the path from the outside in.

Chaining the dots

To access a member buried inside multiple layers, you start with the name of the main variable and work your way down the hierarchy. Each dot represents a layer of ownership.

Here is how you define and access these nested layers:

#include <stdio.h>

struct Dimensions {
    int width;
    int height;
};

struct Window {
    const char* title;
    struct Dimensions size; // This is a nested struct
};

int main() {
    struct Window myApp;

    // Setting a top-level member
    myApp.title = "Game Engine";

    // Accessing a nested member
    // We go from myApp -> size -> width
    myApp.size.width = 1024;
    myApp.size.height = 768;

    printf("Window: %s\n", myApp.title);
    printf("Resolution: %d x %d\n", myApp.size.width, myApp.size.height);

    return 0;
}

How to read the path

When you see myApp.size.width, read it from left to right as a map:

  1. myApp: Start at the main variable.
  2. .size: Look inside myApp for a member named size.
  3. .width: Look inside that size object for a member named width.

You can chain these as deeply as you need (e.g., company.department.employee.salary). The rule remains the same: each dot moves you one step deeper into the hierarchy. If you forget a layer, the compiler will get confused because the outer struct doesn't directly contain the inner data—it only contains the struct that holds that data.

Key takeaway

Access nested members by chaining the dot operator (.) to navigate from the outermost parent down to the specific child member.