![]() |
VOOZH | about |
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.
To dynamically create an array of structs, we can use the malloc() function to dynamically allocate structs into the array of the given size.
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.
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)