C programming - struct

In C programming, a struct (short for "structure") is a user-defined composite data type that groups together related variables under a single name. The variables within a struct can be of different data types and are called "members" or "fields".

To define a struct in C, you use the struct keyword followed by a name for the structure and a set of member declarations enclosed in braces. For example, the following code defines a struct named Person that contains three members: name, age, and gender.

r‮:ot refe‬theitroad.com
struct Person {
    char name[50];
    int age;
    char gender;
};

To declare a variable of a struct type, you simply use the struct name followed by the variable name. For example, the following code declares a variable named person1 of type Person:

struct Person {
    char name[50];
    int age;
    char gender;
};

struct Person person1;

You can access the members of a struct using the dot (.) operator. For example, to set the name member of person1, you would use the following code:

struct Person {
    char name[50];
    int age;
    char gender;
};

struct Person person1;

strcpy(person1.name, "John Doe");

strcpy() is a string function in C that copies a string from one location to another.

You can also initialize a struct variable when you declare it, like this:

struct Person {
    char name[50];
    int age;
    char gender;
};

struct Person person1 = {"John Doe", 30, 'M'};

struct variables can be passed as arguments to functions and returned from functions, just like any other data type.

struct variables are commonly used to group together related data, such as the components of a complex data object or the attributes of a real-world object. They can be used to improve code organization, readability, and maintainability.