twitter
    Find out what I'm doing, Follow Me :)

Nested And Named Structures

Load and display the file named nested.c for an example of a nested structure. The structures we have seen so far have been very simple, although useful. It is possible to define structures containing dozens and even hundreds or thousands of elements but it would be to the programmers advantage not to define all of the elements at one pass but rather to use a hierarchical structure of definition. This will be illustrated with the program on your monitor.
 
main( )
{
struct person {
char name[25];
int age;
char status; /* M = married, S = single */
} ;
struct alldat {
int grade;
struct person descrip;
char lunch[25];
} student[53];
struct alldat teacher,sub;
teacher.grade = 94;
teacher.descrip.age = 34;
teacher.descrip.status = ’M’;
strcpy(teacher.decrip.name,"Mary Smith");
strcpy(teacher.lunch,"Baloney Sandwich");
sub.descrip.age = 87;
sub.descrip.status = ’M’;
strcpy(sub.descrip.name,"Old Lady Brown");
sub.grade = 73;
strcpy(sub.lunch,"Yogurt and toast");
student[1][descrip]age = 15;
student[1][descrip]status = ’S’;
strcpy(student[1][descrip]name,"Billy Boston");
strcpy(student[1]lunch,"Peanut Butter");
student[1][grade] = 77;
student[7][descrip]age = 14;
student[12][grade] = 87;
}


The first structure contains three elements but is followed by no variable name. We therefore have not defined any variables only a structure, but since we have included a name at the beginning of the structure, the structure is named "person". The name "person" can be used to refer to the structure but not to any variable of this structure type. It is therefore a new type that we have defined, and we can use the new type in nearly the same way we use "int", "char", or any other types that exist in C. The only restriction is that this new name must always be associated with the reserved word "struct".

The next structure definition contains three fields with the middle field being the previously defined structure which we named "person". The variable which has the type of "person" is named "descrip". So the new structure contains two simple variables, "grade" and a string named "lunch[25]", and the structure named "descrip". Since "descrip" contains three variables, the new structure actually contains 5 variables. This structure is also given a name "alldat", which is another type definition. Finally we define an array of 53 variables each with the structure defined by "alldat", and each with the name "student". If that is clear, you will see that we have defined a total of 53 times 5 variables, each of which is capable of storing a value.