C Nested Structures

1. What are Nested Structures?

  • A nested structure is a structure that contains another structure as a member.

  • Useful for representing complex data objects like a student with an address, or an employee with a date of joining.

Syntax:

struct Inner {
// members
};
struct Outer {
// members
struct Inner inner_member;
};


2. Example: Student with Nested Date of Birth

#include <stdio.h>
#include <string.h>
struct Date {
int day;
int month;
int year;
};

struct Student {
char name[50];
struct Date dob; // nested structure
};

int main() {
struct Student s1;

strcpy(s1.name, “Alice”);
s1.dob.day = 15;
s1.dob.month = 8;
s1.dob.year = 2005;

printf(“Name: %s\n”, s1.name);
printf(“DOB: %02d-%02d-%d\n”, s1.dob.day, s1.dob.month, s1.dob.year);

return 0;
}

Output:

Name: Alice
DOB: 15-08-2005

3. Nested Structures with Pointers

#include <stdio.h>

struct Date {
int day;
int month;
int year;
};

struct Student {
char name[50];
struct Date *dob; // pointer to nested structure
};

int main() {
struct Date d1 = {15, 8, 2005};
struct Student s1;
s1.dob = &d1;
strcpy(s1.name, “Alice”);

printf(“Name: %s\n”, s1.name);
printf(“DOB: %02d-%02d-%d\n”, s1.dob->day, s1.dob->month, s1.dob->year);

return 0;
}

Output:

Name: Alice
DOB: 15-08-2005

Use -> operator when accessing members through a pointer.


4. Example: Employee with Address

#include <stdio.h>
#include <string.h>
struct Address {
char city[50];
char state[50];
int pin;
};

struct Employee {
char name[50];
int id;
struct Address addr; // nested structure
};

int main() {
struct Employee e1;

strcpy(e1.name, “Bob”);
e1.id = 101;
strcpy(e1.addr.city, “Mumbai”);
strcpy(e1.addr.state, “Maharashtra”);
e1.addr.pin = 400001;

printf(“Employee: %s, ID: %d\n”, e1.name, e1.id);
printf(“Address: %s, %s – %d\n”, e1.addr.city, e1.addr.state, e1.addr.pin);

return 0;
}

Output:

Employee: Bob, ID: 101
Address: Mumbai, Maharashtra - 400001

5. Key Points About Nested Structures

  1. Nested structures allow grouping related structures into one.

  2. Access nested members using dot . operator for normal variables.

  3. Access nested members using arrow -> operator for pointers.

  4. Useful for complex records like employee, student, or product information.

  5. Can be combined with arrays for multiple records.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *