Zone Of Makos

Menu icon

Structures in C

In the C programming language, structures are used to group together related variables of different data types. A structure allows you to create a user-defined data type that can hold multiple pieces of information. Structures provide a way to organize and manipulate complex data in a more organized and convenient manner. In this lesson, we'll explore how to define and use structures in C.

Defining a Structure in C

To define a structure in C, you use the struct keyword followed by the name of the structure and a set of curly braces. Inside the curly braces, you specify the members of the structure, which can be variables of any data type.


struct Student {
    int roll_number;
    char name[50];
    float marks;
};

Accessing Structure Members

Once you have defined a structure, you can create variables of that structure type and access its members using the dot (.) operator. The dot operator allows you to access individual members of a structure variable.


struct Student s1;
s1.roll_number = 1;
strcpy(s1.name, "John");
s1.marks = 85.5;

Structure with Typedef

In C, you can use the typedef keyword along with a structure to create a new type alias. This can make your code more readable and allow you to use the new type name without the need for the struct keyword.


typedef struct {
    int day;
    int month;
    int year;
} Date;

Now, you can declare variables of the Date type directly, without using the struct keyword.


Date d1;
d1.day = 25;
d1.month = 5;
d1.year = 2023;

Conclusion

Structures in C provide a way to group related variables of different data types into a single entity. They allow you to organize and manipulate complex data more effectively. By defining structures, you can create user-defined data types that suit the specific needs of your program. The typedef keyword can be used to create type aliases for structures, making your code more readable. Structures are an important concept in C programming and can be used to represent real-world entities and data structures.