Structures in C

A structure in C is a user-defined data type that groups multiple variables of different types under a single name. It helps organize complex data like records, objects, and database entries.

Why Structures?

Syntax of Structure

struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

Declaring Structure Variable

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

struct Student s1;     // structure variable

Accessing Structure Members

s1.roll = 10;
s1.marks = 89.5;

Use dot (.) operator for accessing structure members.

Initializing a Structure

struct Student s1 = {10, "Sourav", 89.5};

Array of Structures

struct Student s[3];

Used to store multiple records (example: students, employees).

Passing Structure to Function

Real Life Uses

Examples (5 Examples)

Example 1 – Creating and Displaying a Structure

#include <stdio.h>

struct Student {
    int roll;
    float marks;
};

int main() {

    struct Student s = {1, 88.5};

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

    return 0;
}

Example 2 – Structure Input from User

#include <stdio.h>

struct Book {
    char title[30];
    float price;
};

int main() {

    struct Book b;

    printf("Enter title: ");
    fgets(b.title, 30, stdin);

    printf("Enter price: ");
    scanf("%f", &b.price);

    printf("Book: %sPrice: %.2f", b.title, b.price);

    return 0;
}

Example 3 – Array of Structures

#include <stdio.h>

struct Employee {
    int id;
    float salary;
};

int main() {

    struct Employee e[2] = {
        {101, 25000},
        {102, 32000}
    };

    for(int i=0; i<2; i++){
        printf("ID: %d  Salary: %.2f\n", e[i].id, e[i].salary);
    }

    return 0;
}

Example 4 – Passing Structure to Function

#include <stdio.h>

struct Point {
    int x, y;
};

void show(struct Point p){
    printf("X=%d  Y=%d", p.x, p.y);
}

int main() {

    struct Point p1 = {5, 10};
    show(p1);

    return 0;
}

Example 5 – Structure with Pointer

#include <stdio.h>

struct Student {
    char name[20];
    int roll;
};

int main() {

    struct Student s = {"Rahul", 12};
    struct Student *ptr = &s;

    printf("%s %d", ptr->name, ptr->roll);

    return 0;
}