C Programming
In this tutorial we will learn to handle structure in a structure in C programming language.
We have already learned how to create and access members of a structures in the structure tutorial.
Now, lets add a structure inside a structure and learn how to work with it.
In the following example we have a student structure. Inside it we have another structure address to hold the address detail.
student
address
// student structure having address structure inside struct student { char name[255]; char id[20]; // address of the student struct { char line1[255]; char line2[255]; char city[255]; char state[100]; char country[255]; char pincode[20]; } address; };
In the above code snippet we can see that we have an address structure inside the student structure.
We already know by now that to access any member of a structure variable we use the . operator.
.
So, if we want to access the name member of the student structure we have to write the following.
name
std.name
Similarly if we want to access the city member of the address structure which is inside the student structure, we have to write the following.
city
std.address.city
In the following code we will take student detail from the user and then print the output.
#include <stdio.h> int main(void) { // student structure having address structure inside struct student { char name[255]; char id[20]; // address of the student struct { char line1[255]; char line2[255]; char city[255]; char state[100]; char country[255]; char pincode[20]; } address; }; // create structure variable struct student std; // take student data printf("Enter student detail:\n"); printf("Name: "); gets(std.name); printf("ID: "); gets(std.id); printf("Address Line1: "); gets(std.address.line1); printf("Address Line2: "); gets(std.address.line2); printf("City: "); gets(std.address.city); printf("State: "); gets(std.address.state); printf("Country: "); gets(std.address.country); printf("Pincode: "); scanf("%s", std.address.pincode); // display result printf("Student Detail:\n"); printf("Name: %s\n", std.name); printf("ID: %s\n", std.id); printf("\nAddress of the student:\n"); printf("%s\n", std.address.line1); printf("%s\n", std.address.line2); printf("%s, %s %s\n", std.address.city, std.address.state, std.address.country); printf("%s\n", std.address.pincode); return 0; }
Output:
Enter student detail: Name: Yusuf Shakeel ID: s01 Address Line1: House #123 Address Line2: Awesome Street, 1024th Main Road City: Bangalore State: KA Country: India Pincode: 560001 Student Detail: Name: Yusuf Shakeel ID: s01 Address of the student: House #123 Awesome Street, 1024th Main Road Bangalore, KA India 560001