Scroll Progress Bar

Structures

A structure in C is a user-defined data type that allows you to group different variables of different data types under a single name. It enables you to create more complex data structures to represent real-world entities, combining related data into a single unit.

Usage and Syntax:

To define a structure in C, you use the struct keyword followedby the structure name and a list of member variables within curly braces.


struct struct_name {
    data_type member1;
    data_type member2;
    // ...
};
Sample Code with Explanation and Output:

#include <stdio.h>

// Define a structure representing a point in 2D space
struct Point {
    int x;
    int y;
};

int main() {
    // Declare and initialize a structure variable
    struct Point p1 = {3, 7};

    // Accessing structure members using the dot operator
    printf("Point coordinates: x = %d, y = %d\n", p1.x, p1.y);

    // Modifying structure members
    p1.x = 10; // Change the value of x to 10
    p1.y = -5; // Change the value of y to -5

    // Accessing and printing the modified structure members
    printf("Modified Point coordinates: x = %d, y = %d\n", p1.x, p1.y);

    return 0;
}

Output:

Point coordinates: x = 3, y = 7
Modified Point coordinates: x = 10, y = -5
Explanation:
  • In the sample code, define a structure named Point to represent a point in 2D space, having two members: x and y, both of type int.
  • Inside the main function, declare a structure variable p1 of type struct Point and initialize it with values {3, 7} using the curly braces initialization syntax.
  • Access the structure members x and y of p1 using the dot operator (.) and print their values.
  • Next, modify the values of x and y to 10 and -5, respectively.
  • Finally, access and print the modified values of x and y again using the dot operator.
  • Structures are useful when you want to store related pieces of information together, making your code more organized and maintainable.

What is a structure in C?


User-defined

What does a structure group together?


Variables

What is a member of a structure called?


Field

What is used to access structure members?


Dot

Can structures contain members of different types?


Yes