To initialize a structure variable in C, you can use either of the following approaches:
-
Initialization during declaration: You can initialize the structure variable at the time of declaration using curly braces {}. Inside the curly braces, you provide the initial values for each member in the order they are defined in the structure. Here's an example:
struct Person {
char name[50];
int age;
float height;
};
struct Person person1 = {"John Doe", 25, 1.75};
In this example, we define a structure named Person and initialize a structure variable person1 with the initial values "John Doe" for the name member, 25 for the age member, and 1.75 for the height member.
-
Assignment after declaration: If you declare a structure variable without initializing it, you can assign values to its members separately using the assignment operator (=) and the dot (.) operator. Here's an example:
struct Person {
char name[50];
int age;
float height;
};
struct Person person1;
person1.age = 25;
strcpy(person1.name, "John Doe");
person1.height = 1.75;
In this example, we declare a structure variable person1 of type Person and then assign values to its members (age, name, and height) using the dot operator.
Both approaches allow you to initialize the members of a structure variable with their respective values. Choose the method that suits your needs and coding style—either initialize during declaration or assign values after declaration.