Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
85 views
in C Programming by (112k points)
How do you initialize a structure variable?

Please log in or register to answer this question.

1 Answer

0 votes
by (112k points)

To initialize a structure variable in C, you can use either of the following approaches:

  1. 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.

  2. 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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...