C - Structure

structure is a user-defined data type that allows you to group together related variables of different data types under a single name. Structures provide a way to organize and store data that belongs together, making it easier to manage and access. Here's an explanation of structures in C:

Structure Declaration:

To define a structure, you need to declare its structure tag and specify its member variables. The structure tag serves as the new data type name, and the member variables define the components of the structure.

struct structureName {
    dataType member1;
    dataType member2;
    // ...
};

structureName: The name given to the structure.

dataType: The data type of each member variable.

#include <stdio.h>
// Structure declaration
struct Student {
    char name[20];
    int age;
    float gpa;
};
int main() {
    // Structure variable declaration
    struct Student student1;
    // Accessing and modifying structure members
    strcpy(student1.name, "John");
    student1.age = 20;
    student1.gpa = 3.8;
    // Printing structure members
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("GPA: %.2f\n", student1.gpa);
    return 0;
}

In this example, a structure named Student is defined with three member variables: name (a character array), age (an integer), and gpa (a float). Inside main(), a structure variable student1 is declared, and its members are accessed and modified using the dot operator (.). Finally, the structure members are printed using printf().

You can create multiple variables of the structure type and manipulate them independently. Structures allow you to group related data together and access them as a cohesive unit.

Nested Structures:

C structures can also be nested, meaning a structure can have another structure as one of its member variables. This allows you to create more complex data structures that contain multiple levels of organization.

#include <stdio.h>
// Structure declaration
struct Address {
    char city[20];
    char state[20];
};
// Structure declaration with nested structure
struct Person {
    char name[20];
    int age;
    struct Address address;
};
int main() {
    // Structure variable declaration
    struct Person person1;
    // Accessing and modifying nested structure members
    strcpy(person1.name, "Alice");
    person1.age = 25;
    strcpy(person1.address.city, "New York");
    strcpy(person1.address.state, "NY");
    // Printing structure members
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Address: %s, %s\n", person1.address.city, person1.address.state);
    return 0;
}

In this example, the Person structure is defined with two member variables: name and age, along with a nested structure Address. The Address structure has two member variables: city and state. The program demonstrates how to access and modify the nested structure members.