Structures and Nested Structures in C Programming (Complete Guide with Examples)


This tutorial explains structures in C, which allow grouping different data types into a single unit. It also covers nested structures, where a structure contains another structure, helping beginners manage complex data efficiently.

1. What is a Structure

  1. A structure (struct) is a user-defined data type that groups variables of different types under a single name.
  2. Syntax:

struct structure_name {
data_type member1;
data_type member2;
...
};

Example: Basic Structure


#include <stdio.h>

struct Student {
int id;
char name[50];
float marks;
};

int main() {
struct Student s1;

s1.id = 101;
strcpy(s1.name, "Muni");
s1.marks = 95.5;

printf("ID: %d\n", s1.id);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);

return 0;
}

Output:


ID: 101
Name: Muni
Marks: 95.50

2. Nested Structures

  1. A nested structure is a structure that contains another structure as a member.
  2. Useful for complex data representation.

Syntax:


struct Outer {
int id;
struct Inner {
char name[50];
float marks;
} student;
};

Example: Nested Structure


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

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

struct Student {
int id;
char name[50];
struct Date dob; // Nested structure
};

int main() {
struct Student s1;

s1.id = 101;
strcpy(s1.name, "Muni");
s1.dob.day = 15;
s1.dob.month = 12;
s1.dob.year = 1990;

printf("ID: %d\n", s1.id);
printf("Name: %s\n", s1.name);
printf("Date of Birth: %d-%d-%d\n", s1.dob.day, s1.dob.month, s1.dob.year);

return 0;
}

Output:


ID: 101
Name: Muni
Date of Birth: 15-12-1990

3. Key Points to Remember

  1. Structures can combine different data types into one unit
  2. Nested structures allow hierarchical data modeling
  3. Members of a nested structure are accessed using the dot operator
  4. Structures can be used in arrays, pointers, and functions for more complex programs