Open In App

How to Create a Dynamic Array of Structs?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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;
}


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads