đ️ 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
- Declare a structure to hold employee data and display it.
- Write a program to input and print details of 5 students using an array of structures.
- 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.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ