C - Nested Structures

Overview

Structures in C can contain other structures as members, allowing you to model complex data relationships.

Learning Objectives

  • Declare and initialize nested structs.
  • Access nested members and pass nested structs to functions.

Prerequisites

Example

#include <stdio.h>

struct Date { int day, month, year; };
struct Student { char name[50]; struct Date dob; };

int main(void) {
    struct Student s = {"Alice", {15, 8, 2000}};
    printf("%s was born on %d/%d/%d\n", s.name, s.dob.day, s.dob.month, s.dob.year);
}

Real-time Use Case: Employee Records

#include <stdio.h>

struct Address { char street[100]; char city[50]; int zip; };
struct Employee { char name[50]; int id; struct Address address; };

int main(void) {
  struct Employee emp = {"Bob Smith", 101, {"123 Main St", "Springfield", 12345}};
  printf("Employee: %s\nID: %d\nAddress: %s, %s, %d\n",
         emp.name, emp.id, emp.address.street, emp.address.city, emp.address.zip);
}

Checks for Understanding

  1. How do you access the zip of struct Employee e?
Show answer

e.address.zip

Expected Output

Alice was born on 15/8/2000
Employee: Bob Smith
ID: 101
Address: 123 Main St, Springfield, 12345

Common Pitfalls

  • Initializer braces must match nested structure layout precisely.
  • Copying a struct performs a shallow copy; embedded structs are copied by value.
  • Alignment and padding can affect size; avoid assuming byte layouts.
  • Prefer pointers for large nested structs to avoid heavy copying.

Exercises

  1. Define struct Course and struct Student with a nested course; print details.
  2. Write a function that updates a nested address inside an employee struct.