STRUCTURES IN C
✓ Definition
A structure in C is a user-defined data type that groups different types of variables under a single name.
It is used to store heterogeneous (different types) data.
✓ Why Structures?
Because arrays can store only one data type, but structures can store multiple different data types.
Example: Student record → name (string), roll (int), marks (float)
✓ Syntax
struct structure_name {
data_type variable1;
data_type variable2;
...
};
✓ Example
struct student {
int roll;
char name[20];
float marks;
};
✓ Declaring Structure Variables
struct student s1, s2;
✓ Accessing Structure Members
Use dot operator (.)
[Link] = 10;
scanf("%s", [Link]);
printf("%f", [Link]);
2. Initializing Structures
struct student s1 = {101, "Aman", 89.5};
3. Array of Structures
struct student s[3];
4. Passing Structure to Function
(a) Pass by value
void display(struct student s1);
(b) Pass by reference
void display(struct student *s1)
5. Nested Structures
A structure inside another structure.
struct address {
char city[20];
int pincode;
};
struct student {
char name[20];
struct address add;
};
6. Memory Allocation of Structures
Each member gets separate memory.
Example:
struct test {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte (+ padding)
};