6.1) Structure in C

A structure is a user-defined data type that groups together variables of different data types under a single name.

Each variable within a structure is referred to as a member.

Structures allow you to create complex data structures to represent real-world entities.

Let’s dive into structures with simple explanations and code examples:

Defining a Structure

To define a structure, you use the struct keyword followed by the structure’s name.

Inside the structure, you list the members along with their data types.

Example: Defining a Structure

#include <stdio.h>

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

int main() {
    // Declare a structure variable 'person1'
    struct Person person1;

    // Assign values to structure members
    strcpy(person1.name, "Alice");
    person1.age = 25;
    person1.height = 5.6;

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

    return 0;
}

Output:

Name: Alice
Age: 25
Height: 5.60

Accessing Structure Members

You can access the members of a structure using the dot (.) operator.

Example: Accessing Structure Members

#include <stdio.h>

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

int main() {
    struct Student student1;

    strcpy(student1.name, "Bob");
    student1.roll = 101;
    student1.marks = 85.5;

    printf("Name: %s\n", student1.name);
    printf("Roll: %d\n", student1.roll);
    printf("Marks: %.2f\n", student1.marks);

    return 0;
}

Output:

Name: Bob
Roll: 101
Marks: 85.50

Initializing Structures

You can initialize a structure while declaring it, using curly braces.

Example: Initializing Structures

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1 = {3, 7};

    printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);

    return 0;
}

Output:

Point coordinates: (3, 7)

Nested Structures

You can create structures within structures, forming nested structures.

Example: Nested Structures

#include <stdio.h>

struct Address {
    char city[50];
    char state[50];
};

struct Employee {
    char name[50];
    int empId;
    struct Address address;
};

int main() {
    struct Employee employee1;

    strcpy(employee1.name, "John");
    employee1.empId = 1001;
    strcpy(employee1.address.city, "New York");
    strcpy(employee1.address.state, "NY");

    printf("Name: %s\n", employee1.name);
    printf("Employee ID: %d\n", employee1.empId);
    printf("City: %s\n", employee1.address.city);
    printf("State: %s\n", employee1.address.state);

    return 0;
}

Output:

Name: John
Employee ID: 1001
City: New York
State: NY

Using structures, you can organize and manipulate data in a more meaningful and structured way. They are especially useful for representing entities that have multiple attributes.

Leave a Reply