- Asked 7/16
- 2070 Asar · 2 marks
- 2073 Chaitra · 2 marks
- 2073 Shrawan · 4 marks
- 2067 Asoj · 2 marks
- 2072 Kartik · 3 marks
- 2070 Chaitra · 1 mark
- 2074 Asoj · 3 marks
Nested structures with example
Short answer
Nested structures contain another structure as a member, useful for hierarchical data like a date inside a student record. Define the inner structure first, then declare it in the outer; access members with dot operators, e.g., s.dob.month.
What do you mean by nested structures? Explain nested structure with suitable example. (Need of nested structure; how can we create and use a structure within another.)
Meaning
A nested structure is a structure that has another structure as one of its members. The inner structure must be defined before it is used in the outer structure.
Need
- Real-world data is often hierarchical: a student has a date of birth, which itself has day, month and year; an employee has an address.
- It groups related data, reuses one structure (such as
date) in many places, and keeps the program readable.
Creating a nested structure
struct date { int day, month, year; };
struct student {
char name[30];
int roll;
struct date dob; /* structure inside structure */
};
(The inner structure can also be defined inside the outer one.)
Using it
Members are reached by repeating the dot operator from the outside in: s.dob.month. It can be initialised with nested braces: {"Sita", 12, {5, 8, 2005}}.
#include <stdio.h>
struct date {
int day, month, year;
};
struct student {
char name[30];
int roll;
struct date dob; /* nested structure */
};
int main(void)
{
struct student s = {"Sita", 12, {5, 8, 2005}};
printf("Name: %s, Roll: %d\n", s.name, s.roll);
printf("DOB : %d/%d/%d\n", s.dob.day, s.dob.month, s.dob.year);
return 0;
}
Output:
Name: Sita, Roll: 12
DOB : 5/8/2005
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Define structure; need of structures · Computer Programming, chapter 8 · asked 2×
- Arrays within structures · Computer Programming, chapter 8
- College records with nested date structure · Computer Programming, chapter 8
- Height difference using nested structure · Computer Programming, chapter 8
- Nested function · Computer Programming, chapter 6
- Sort employee structures by salary · Computer Programming, chapter 8 · asked 2×
- Why do we need DFT · Digital Signal Analysis and Processing, chapter 7 · asked 6×
- Why do we need FFT · Digital Signal Analysis and Processing, chapter 7 · asked 2×
- Project financing; structures; capital structure steps · Project Engineering, chapter 6
- Drop structures: need and types with sketches · Irrigation and Drainage Engineering, chapter 7 · asked 6×