Structures in C
Structures in C
Introduction
In C programming, sometimes we need to store different types of data together.
This is done using structures.
👉 Structures allow grouping of different data types into a single unit.
What is a Structure?
A structure is:
👉 A user-defined data type that groups different data types together
Why Use Structures?
- ✔ Store related data together
- ✔ Handle complex data easily
- ✔ Improve code organization
- ✔ Useful in real-world applications
Syntax of Structure
struct structure_name {
data_type member1;
data_type member2;
};
Example: Structure Declaration & Usage
#include <stdio.h>
struct Student {
int id;
char name[20];
float marks;
};
int main() {
struct Student s1 = {1, "Dharani", 85.5};
printf("ID = %d\n", s1.id);
printf("Name = %s\n", s1.name);
printf("Marks = %.2f\n", s1.marks);
return 0;
}
Output
ID = 1
Name = Dharani
Marks = 85.50
Accessing Structure Members
👉 Use dot (.) operator
s1.id
s1.name
s1.marks
Array of Structures
#include <stdio.h>
struct Student {
int id;
float marks;
};
int main() {
struct Student s[2] = {
{1, 80.5},
{2, 90.0}
};
int i;
for (i = 0; i < 2; i++) {
printf("ID = %d, Marks = %.1f\n", s[i].id, s[i].marks);
}
return 0;
}
Output
ID = 1, Marks = 80.5
ID = 2, Marks = 90.0
Pointer to Structure
#include <stdio.h>
struct Student {
int id;
};
int main() {
struct Student s1 = {10};
struct Student *ptr = &s1;
printf("ID = %d", ptr->id);
return 0;
}
Output
ID = 10
👉 -> is used with pointer
Structure vs Array Table
| Feature | Structure | Array |
|---|---|---|
| Data Type | Different types | Same type |
| Access | Using dot operator | Using index |
| Purpose | Group different data | Store similar data |
Important Notes
- Structure size depends on members
-
Use
.for variable -
Use
->for pointer - Can contain arrays and pointers
Common Mistakes
-
❌ Forgetting
structkeyword - ❌ Wrong member access
- ❌ Not initializing properly
-
❌ Confusing
.and->
Pro Tips
- ✔ Use structures for real-world data
- ✔ Combine with arrays & pointers
- ✔ Use meaningful names
- ✔ Practice structure programs
Conclusion
Structures are essential for handling complex data in C. They help organize and manage related data efficiently.
Master structures to build real-world applications.
👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.
Comments
Post a Comment