Nesting of strucutres
A program to demonstrate nested structures with one structure called within another structure.
Learning Objectives
- Understanding nesting of structure with a simple example.
Source Code
|
Run Output
Code Understanding
struct Name { char fname[40]; char lname[40];};
Structure Name has two char arrays fname and lname. This has been given above another structure where it will be used while nesting.
struct Person { Name name; int age; };
This is another structure which contains the structure Name and an additional variable.
Person p1; //This is instance of the nested structure Person.
strcpy(p1.name.fname,”Raju”);
Here we are filling value in the fname variable within the declared object name of instance p1. The nesting effect with multi-level access using the dot (.) operator is visible here.
strcpy(p1.name.lname,”Verma”);
Here we are doing the same thing for lname within name within p1.
p1.age=40;
Here we are filling the p1.age which is directly within Person structure.
cout<<p1.name.fname<<” “<<p1.name.lname <<“, “<<p1.age<<endl;
Here we are printing two variables as its nested two level forms and other one directly.
Notes
- Multiple levels of nesting is permitted. However beyond a point it can give rise to un-manageable level of program complexity.
Common Errors
- The nesting syntax has to be given on object names only and not the structure name. For e.g. giving thing like Person.Name.fname would be incorrect in this example. It has to be p1.name.fname .
- Notice that Name is a structure definition and name is the instance based on Name. This we are able to do as c++ is case-sensitive.
Suggested Filename(s): strucnest.cpp
sunmitra| Created: 22-Jan-2018 | Updated: 22-Jan-2018|