Getting Started With C

In C, you can initialize a structure either at the time of declaration or later using an assignment. Here's an overview of both methods:

• Initialization at Declaration:

When you declare a structure, you can provide initial values for its members in the same line. Here's an example:

  • Examples :

    Program.c


  • In this example, the structure Point has two members (x and y), and they are initialized with the values 3 and 7, respectively.

    • Initialization after Declaration:

    You can also initialize a structure after declaration using the assignment operator. Here's an example:

  • Examples :

    Program.c


  • Output:

            Coordinates: (5, 10)
            In this example, the structure Point is declared first, and then its members x and y are initialized with the values 5 and 10, respectively.
            
          
          

    Resources :

    Test Your Knowledge
    Choose The

    With supporting text below as a natural lead-in to additional content.

    Q1. struct Point { int x; int y; }; int main() { struct Point p = {1, 2}; printf("%d, %d", p.x, p.y); return 0; }

    Q2. struct Student { char name[20]; int age; float marks; }; int main() { struct Student s = {.name="John", .age=20, .marks=85.5}; printf("%s, %d years, %.2f marks", s.name, s.age, s.marks); return 0; }