🏗️ Declaring and Using Structures in C

🏗️ Declaring and Using Structures in C

Structures in C are user-defined data types that allow grouping variables of different types under a single name. This is especially useful for modeling real-world entities like a student, employee, or book.


📌 What is a Structure?

A structure allows you to bundle related data. For example, a student’s record may contain a name, roll number, and marks—all of different data types.


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

Here, Student is a structure with three members: name, roll, and marks.


🔰 Declaring Structure Variables


struct Student s1;  // Declare a variable s1 of type struct Student

You can also declare and initialize:


struct Student s1 = {"Rahim", 101, 89.5};

đŸ§Ē Example: Structure Declaration and Usage


#include <stdio.h>

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

int main() {
    struct Student s1;

    // Input data
    printf("Enter name: ");
    gets(s1.name);
    printf("Enter roll number: ");
    scanf("%d", &s1.roll);
    printf("Enter marks: ");
    scanf("%f", &s1.marks);

    // Output data
    printf("\nStudent Info:\n");
    printf("Name: %s\n", s1.name);
    printf("Roll: %d\n", s1.roll);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

📌 Note:

gets() is unsafe and deprecated; prefer fgets() in modern code.


đŸ‘Ĩ Array of Structures

You can create an array of structures to store data of multiple students.


struct Student students[3];

for (int i = 0; i < 3; i++) {
    printf("Enter name, roll and marks for student %d:\n", i+1);
    scanf("%s %d %f", students[i].name, &students[i].roll, &students[i].marks);
}

🔗 Passing Structures to Functions

By value: Copies the entire structure.


void display(struct Student s) {
    printf("%s %d %.2f\n", s.name, s.roll, s.marks);
}

By reference: More efficient and allows modification.


void modify(struct Student *s) {
    s->marks += 5;  // Increase marks
}

đŸ“Ļ Nested Structures

You can include one structure inside another.


struct Date {
    int day, month, year;
};

struct Student {
    char name[50];
    int roll;
    struct Date dob;
};

🧩 Practice Problems

  1. Declare a structure to hold employee data and display it.
  2. Write a program to input and print details of 5 students using an array of structures.
  3. Create a nested structure for a person including name, age, and address (with city and postal code).

🧠 Summary

  • struct is used to define a custom data type.
  • You can create arrays of structures and pass them to functions.
  • Structures make code modular and organized, especially for large data sets.
c structure tutorial, declaring structure in c, struct example c, nested structure in c, student struct c, pass structure to function, array of structures in c

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ