VOOZH about

URL: https://www.geeksforgeeks.org/c/how-to-create-dynamic-array-of-structs-in-c/

⇱ How to Create a Dynamic Array of Structs? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a Dynamic Array of Structs?

Last Updated : 23 Jul, 2025

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.

Create a Dynamic Array of Structs in C

A dynamic array of structs in C combines dynamic arrays and structures to organize and store multiple pieces of related information, each being implemented as a structure.

We can create a dynamic array of structs using the malloc() funciton. This function takes the required size of the memory as an argument and returns the void pointer to the allocated memory. We can then convert this pointer to struct type using typecasting.

Note: When the usage of dynamic array is done, free the allocated memory to avoid memory leaks.

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.


Output
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.

Comment