![]() |
VOOZH | about |
In C, a struct is a user-defined data type that allows the users to group related data in a single object. An array of structs allows to store multiple structs in contiguous memory locations. In this article, we will learn how to add an element to an array of structs in C.
Example:
Input:
structArray[] = { { "Ram", 21 }, { "Rohit", 25 } };
Element to add: new_person = { "Sia", 24 };
Output:
structArray: Name: Ram, Age: 21
Name: Rohit, Age: 25
Name: Sia, Age: 24
One structure can be assigned to the other using the assignment operator. We can add elements to the array of structures by assigning them to the required index.
The following program illustrates how we can add an element to an array of structs in C.
Original Array of Struct: Name: Ram, Age: 21 Name: Rohit, Age: 25 After Addition Array of struct: Name: Ram, Age: 21 Name: Rohit, Age: 25 Name: Sia, Age: 24
Time Complexity: O(1)
Auxiliary Space: O(1)