How to Initialize Array of Structs in C?
Last Updated :
28 Feb, 2024
In C, arrays are data structures that store the data in contiguous memory locations. While structs are used to create user-defined data types. In this article, we will learn how to initialize an array of structs in C.
Initializing Array of Structures in C
We can initialize the array of structures using list initialization where each of the nested lists corresponds to the members of a single structure element.
Syntax to Initialize Array of Structs in C
struct Str str[] = {
{structure1_value1, structure1_value2},
{structure2_value1, structure2_value2},
{structure3_value1, structure3_value2}
};
C Program to Initialize an Array of Structs
The below example demonstrates how we can initialize an array of structures in C.
C
#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main()
{
struct Student students[] = { { "John" , 1, 85.5 },
{ "Emma" , 2, 90.6 },
{ "Harry" , 3, 92.7 } };
printf ( "Students: \n" );
for ( int i = 0; i < 3; i++) {
printf ( "Name: %s, Roll: %d, Marks: %.2f\n" ,
students[i].name, students[i].roll,
students[i].marks);
}
return 0;
}
|
Output
Students:
Name: John, Roll: 1, Marks: 85.50
Name: Emma, Roll: 2, Marks: 90.60
Name: Harry, Roll: 3, Marks: 92.70
Time Complexity: O(N), where N is the size of the array.
Space Complexity: O(1) as no extra space for utilization is required.
Share your thoughts in the comments
Please Login to comment...