Structures Part 2

Nested Structure in C: Struct inside another struct

You can use a structure inside another structure, which is fairly possible. As I explained above that once you declared a structure, the struct struct_name acts as a new data type so you can include it in another struct just like the data type of other data members. Sounds confusing? Don’t worry. The following example will clear your doubt.

Example of Nested Structure in C Programming

Lets say we have two structure like this:
Structure 1: stu_address

struct stu_address
{
     int street;
     char *state;
     char *city;
     char *country;
}

Structure 2: stu_data

struct stu_data
{
    int stu_id;
    int stu_age;
    char *stu_name;
    struct stu_address stuAddress;
}

As you can see here that I have nested a structure inside another structure.

Assignment for struct inside struct (Nested struct)

Lets take the example of the two structure that we seen above to understand the logic

struct  stu_data  mydata;
mydata.stu_id = 1001;
mydata.stu_age = 30;
mydata.stuAddress.state = "UP"; //Nested struct assignment
..

How to access nested structure members?

Using chain of “.” operator.
Suppose you want to display the city alone from nested struct –

printf("%s",  mydata.stuAddress.city);

Use of typedef in Structure

typedef makes the code short and improves readability. In the above discussion we have seen that while using structs every time we have to use the lengthy syntax, which makes the code confusing, lengthy, complex and less readable. The simple solution to this issue is use of typedef. It is like an alias of struct.

Code without typedef

struct home_address {
  int local_street;
  char *town;
  char *my_city;
  char *my_country;
};
...
struct home_address var; 
var.town = "Agra";

Code using tyepdef

typedef struct home_address{
  int local_street;
  char *town;
  char *my_city;
  char *my_country;
}addr;
..
..
addr var1;
var.town = "Agra";

Instead of using the struct home_address every time you need to declare struct variable, you can simply use addr, the typedef that we have defined.

Designated initializers to set values of Structure members

We have already learned two ways to set the values of a struct member, there is another way to do the same using designated initializers. This is useful when we are doing assignment of only few members of the structure. In the following example the structure variable s2 has only one member assignment.

#include <stdio.h>
struct numbers
{
   int num1, num2;
};
int main()
{
   // Assignment using using designated initialization
   struct numbers s1 = {.num2 = 22, .num1 = 11};
   struct numbers s2 = {.num2 = 30};
 
   printf ("num1: %d, num2: %d\n", s1.num1, s1.num2);
   printf ("num1: %d", s2.num2);
   return 0;
}

Output:

num1: 11, num2: 22
num1: 30

Comments