Structs

Lesson 21
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

In C, a struct is a user-defined composite data type that groups together variables of different data types under a single name. It allows you to define a group of related variables that can be accessed and manipulated as a single unit. A struct can be thought of as a container that holds related data.

The syntax for defining a struct is as follows:

struct struct_name {
    data_type member1;
    data_type member2;
    // ...
};

Here, struct_name is the name of the struct, and member1, member2, etc. are the names of the members of the struct, which can be of any data type.

To access the members of a struct, you use the dot operator (.) with the name of the struct variable and the name of the member. For example:

struct person {
    char name[50];
    int age;
};

int main() {
    struct person p1;
    strcpy(p1.name, "John");
    p1.age = 30;
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);
    return 0;
}

In this example, we define a person struct with two members: a character array name to store the person’s name, and an integer age to store their age. We then create a variable p1 of type person and set its name and age members using the dot operator. Finally, we print out the values of p1’s name and age members using printf.

Structs can be useful for organizing related data and passing it around as a single unit in your program. They can also be used to create more complex data structures, such as linked lists and trees.