Structures in C Programming
In C, a structure is a user-defined data type that allows you to group different types of variables under a single name. It is very useful when you want to represent a real-world entity (like a student, employee, or gene record) with multiple attributes.
### **Structures in C Programming**
In **C**, a **structure** is a user-defined data type that allows you to group **different types of variables** under a single name. It is very useful when you want to represent a real-world entity (like a student, employee, or gene record) with multiple attributes.
---
## **1. Definition of Structure**
A structure is defined using the `struct` keyword.
```c
struct Student {
int roll_no;
char name[50];
float marks;
};
```
Here, `Student` is a structure that contains **int, char array, and float**.
---
## **2. Declaring Structure Variables**
```c
struct Student s1, s2;
```
OR during definition:
```c
struct Student {
int roll_no;
char name[50];
float marks;
} s1, s2;
```
---
## **3. Accessing Structure Members**
Use the **dot (.) operator**.
```c
s1.roll_no = 101;
s1.marks = 85.5;
strcpy(s1.name, "Amina");
```
---
## **4. Structure Initialization**
```c
struct Student s1 = {101, "Amina", 85.5};
```
---
## **5. Array of Structures**
Used to store multiple records.
```c
struct Student s[3];
for(int i = 0; i < 3; i++) {
scanf("%d %s %f", &s[i].roll_no, s[i].name, &s[i].marks);
}
```
---
## **6. Structures and Functions**
### Passing structure to a function
```c
void display(struct Student s) {
printf("%d %s %.2f", s.roll_no, s.name, s.marks);
}
```
### Passing structure by reference
```c
void display(struct Student *s) {
printf("%d %s %.2f", s->roll_no, s->name, s->marks);
}
```
---
## **7. Structure Pointer**
```c
struct Student s1;
struct Student *ptr = &s1;
ptr->roll_no = 102;
```
(`->` is called the **arrow operator**)
---
## **8. Nested Structures**
Structure inside another structure.
```c
struct Address {
char city[20];
int pincode;
};
struct Student {
int roll_no;
struct Address addr;
};
```
---
## **9. typedef with Structure**
Used to avoid writing `struct` repeatedly.
```c
typedef struct {
int id;
float salary;
} Employee;
Employee e1;
```
---
## **10. Advantages of Structures**
* Groups related data
* Improves program readability
* Useful for large programs and data management
* Widely used in **file handling**, **databases**, and **bioinformatics data structures**
---
## **11. Structure vs Union (Short Note)**
| Structure | Union |
| -------------------------------- | ------------------------------ |
| Each member has its own memory | Members share same memory |
| Larger size | Sm-
### **Conclusion – Structures in C Programming**
Structures in C provide an efficient way to store and manage related data of different data types under a singl