Open In App

How to Dynamically Create Array of Structs in C?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, an array is a data structure that stores the collection of elements of similar types. Structs in C allow the users to create user-defined data types that can contain different types of data items. In this article, we will learn how we can create an array of structs dynamically in C.

Dynamically Create Array of Structs in C

To dynamically create an array of structs, we can use the malloc() function to dynamically allocate structs into the array of the given size.

Syntax of malloc()

malloc(size_in_bytes);

The malloc function returns the pointer of void type to the memory allocated of the given size. We then use typecasting to cast this pointer to the desired type which here is the pointer to struct.

C Program to Dynamically Create Array of Structs

C




// C program to dynamically create array of structs
  
#include <stdio.h>
#include <stdlib.h>
struct Student {
    int id;
    char name[50];
};
int main()
{
    // Decalre the size of array
    int size = 5;
  
    // Initialize an array of structs
    struct Student* myArray = (struct Student*)malloc(
        size * sizeof(struct Student));
    if (myArray == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }
  
    // Intialize data to structs present in the array
    for (int i = 0; i < size; i++) {
        myArray[i].id = i + 1;
        snprintf(myArray[i].name, sizeof(myArray[i].name),
                 "Student%d", i + 1);
    }
    // Print the data of structs present in the array
    printf("Array Elements:\n");
    for (int i = 0; i < size; i++) {
        printf("Element %d: ID = %d, Name = %s\n", i + 1,
               myArray[i].id, myArray[i].name);
    }
    free(myArray);
    return 0;
}


Output

Array Elements:
Element 1: ID = 1, Name = Student1
Element 2: ID = 2, Name = Student2
Element 3: ID = 3, Name = Student3
Element 4: ID = 4, Name = Student4
Element 5: ID = 5, Name = Student5

Time Complexity: O(N) where N is the number of elements present in the array
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads