C Program to Create a Dynamic Array of Structs
The below example demonstrates how we can initialize and access members of a dynamic array of structures in C.
C
// C program to declare and use dynamic array of structure #include <stdio.h> #include <stdlib.h> // Define a structure to represent a student struct Student { char name[50]; int age; }; int main() { // Declaring a pointer to a structure and allocating // memory for initial (3) students struct Student* students = ( struct Student*) malloc (3 * sizeof (*students)); // Check for malloc Failure if (students == NULL) { fprintf (stderr, "Memory allocation failed\n" ); return 1; } // Providing some sample data for the students for ( int i = 0; i < 3; i++) { snprintf(students[i].name, sizeof (students[i].name), "Student%d" , i + 1); students[i].age = 20 + i; } // Displaying the student data printf ( "Student Data:\n" ); for ( int i = 0; i < 3; i++) { printf ( "Student %d: Name - %s, Age - %d\n" , i + 1, students[i].name, students[i].age); } // free the memory when done free (students); return 0; } |
Student Data: Student 1: Name - Student1, Age - 20 Student 2: Name - Student2, Age - 21 Student 3: Name - Student3, Age - 22
Explanation: In the above example we defined the Student
structure and dynamically allocates memory for an array of three Student
instances. It populates each student’s data using a loop and snprintf
for names and sequential ages. The student information is displayed using another loop. Finally, it frees the allocated memory to prevent memory leaks.
How to Create a Dynamic Array of Structs?
In C, we have dynamic arrays in which we can allocate an array of elements whose size is determined during runtime. In this article, we will learn how to create a dynamic array of structures in C.