Structures in C Programming

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Structures

Structs: Defining and using custom data types to group related variables.

Structures (or structs) in C are used to define custom data types that group related variables. Each variable within a structure is called a member, and the members can be of different types. Structures are useful for organizing complex data into a single unit, making it easier to manage and manipulate related data.

Defining and Using Structures

Here's a step-by-step explanation with an example:

1. Define a Structure

#include <stdio.h>

// Define a structure named 'Person'
struct Person {
    char name[50];
    int age;
    float height;
};
            

In this example, the Person structure has three members:

2. Declare and Initialize Structure Variables

int main() {
    // Declare and initialize a structure variable
    struct Person person1 = {"Alice", 30, 5.5};

    // Access and print the members of the structure
    printf("Name: %s\\n", person1.name);
    printf("Age: %d\\n", person1.age);
    printf("Height: %.2f\\n", person1.height);

    return 0;
}
            

Here, person1 is a variable of type struct Person. It is initialized with values for name, age, and height. The members of the structure are accessed using the dot operator (.).

3. Using Pointers to Structures

int main() {
    // Declare and initialize a structure variable
    struct Person person1 = {"Bob", 25, 5.8};
    
    // Declare a pointer to a structure
    struct Person *ptr = &person1;

    // Access and modify the members using the pointer
    printf("Name: %s\\n", ptr->name);
    printf("Age: %d\\n", ptr->age);
    printf("Height: %.2f\\n", ptr->height);

    // Modify the structure members using the pointer
    ptr->age = 26;
    printf("Updated Age: %d\\n", ptr->age);

    return 0;
}
            

In this example:

Previous Next
Modern Footer