Nesting of Structures in C

A Structure can contain other Structure variables as members. This is called Nesting of Structures. For example address structure is a structure. We can define a nested structure called customer which contains address structure as follows:

struct address
{
int house_number;
char street_name[50];
int zip_code;
char country[50];
};
struct customer
{
char name[50];
structure address billing_addr;
structure address shipping_addr;
};
struct customer cust1;

If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure.

cust1.billing_addr.house_number = 10;

It should be noted that a structure definition can’t contain the variable of its own type as a data member. This means the following structure definition is illegal.

struct address
{
int house_number;
char street_name[50];
int zip_code;
char country[50];
struct address old_address;
/* The statement above is illegal*/
};

Program 1 shows a simple program to define a structure, declare a structure variable, initialize and access members. It is followed by screenshot of the output.

#include<stdio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
void main()
{
struct student s1 = {“abc”, 1, 450};
struct student s2;
printf(“Enter student Name, Rollno,
Marks:\n”);
scanf(“%s%i%f”, &s2.name, &s2.rollno,
&s2.marks);
printf(“\nStudent Name\tRollno\tMarks
\n”);
printf(“%s\t%i\t%f”, s1.name,
s1.rollno, s1.marks);
printf(“\n”);
printf(“%s\t%i\t%f”,s2.name,

s2.rollno,s2.marks);
}

Program 1: Program to show usage and working of structure

Screenshot from 2020-07-20 22-24-40


For any query or issue, feel free to discuss on http://discuss.eduguru.in