How to Dynamically Create Array of Structs in C?
Last Updated :
22 Feb, 2024
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
#include <stdio.h>
#include <stdlib.h>
struct Student {
int id;
char name[50];
};
int main()
{
int size = 5;
struct Student* myArray = ( struct Student*) malloc (
size * sizeof ( struct Student));
if (myArray == NULL) {
fprintf (stderr, "Memory allocation failed\n" );
return 1;
}
for ( int i = 0; i < size; i++) {
myArray[i].id = i + 1;
snprintf(myArray[i].name, sizeof (myArray[i].name),
"Student%d" , i + 1);
}
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)
Share your thoughts in the comments
Please Login to comment...