Nested Structure in C
Hello Everyone, In this article, we will discuss Nested Structure in C Programming. A nested structure is a structure within another structure, allowing you to create more complex data models by combining related information. We will cover how to define and use nested structures, their benefits, and provide examples to help you understand this powerful feature. Whether you are new to C or have some experience, this guide will help you to understand basics of Array of Structures in C effectively with examples. Let’s get started.
A structure in C programming can be nested in multiple ways, depending on the complexity of the data you want to represent. Here, we will discuss a few common ways of nesting structures and how to access them, as well as how to pass structures to functions.
- Simple nesting: This is when a structure is nested inside another structure directly, as shown in the previous example.
- Array of structures inside a structure: This is useful when you want to store multiple instances of a structure inside another structure.
- Structure containing a pointer to another structure: This can be used to create dynamic structures or to create links between structures.
To access nested structures, you can use the dot (.) operator. If the nested structure is a pointer, use the arrow (->) operator instead.
Now, let’s see an example of passing a structure to a function:
#include <stdio.h>struct Address {
char street[50];
char city[50];
char state[3];
int zip;
};
struct Person {
char name[50];
int age;
struct Address address;
};
// Function to print person's information
void print_person_info(struct Person p) {
printf("Name: %s\\n", p.name);
printf("Age: %d\\n", p.age);
printf("Street: %s\\n", p.address.street);
printf("City: %s\\n", p.address.city);
printf("State: %s\\n", p.address.state);
printf("ZIP: %d\\n", p.address.zip);
}
int main() {
struct Person person1 = {"John Doe", 30, {"123 Main St", "New York", "NY", 10001}};
print_person_info(person1);
return 0;
}
Output:
Name: John Doe
Age: 30
Street: 123 Main St
City: New York
State: NY
ZIP: 10001
In this example, we define two structures: Address and Person. The Person structure has a nested Address structure. We create a function called print_person_info that takes a Person structure as an argument and prints its details. In the main function, we create a Person instance named person1 and pass it to the print_person_info function.