How to Initialize Structures in C?
Last Updated :
06 Mar, 2024
In C, a structure (struct) is a user-defined data type that allows us to combine data items of different data types into a single unit. In this article, we will learn how to initialize structures in C.
Initialize Structures in C
We can initialize the structure by providing the values of the members in the list during the declaration. The values in the list will be then assigned to the member of the structure sequentially. It means the first value in the list will be assigned to the first member and so on.
To initialize the structure member non-sequentially, we can use the designated initialization technique where we initialize the members using their names.
Syntax to Initialize Structures in C
structName varName = {value1, value2, value3 ..., valueN);
Designated Initialization:
struct_type obj_name = {
.member1 = value1, .member2 = value2, member3 = value3,
...... .memberN = valueN
};
C Program to Initialize Structures
C
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float percentage;
};
int main()
{
struct Student student1 = { 1, "John Doe" , 85.5 };
printf ( "ID: %d\n" , student1.id);
printf ( "Name: %s\n" , student1.name);
printf ( "Percentage: %.2f\n" , student1.percentage);
return 0;
}
|
Output
ID: 1
Name: John Doe
Percentage: 85.50
Time Complexity: O(N), where N is the number of members in the struct.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...