Introduction
A structure in C is a user-defined data type that allows storing multiple variables of different data types under a single name. Structures are useful for organizing complex data like student records, employee details, or product information.
Key Points
1. Structure Declaration
- Syntax:
struct StructureName { dataType member1; dataType member2; ... }; - Example:
struct Student { int id; char name[20]; float marks; };
2. Structure Variables
- Declare variables of the structure type:
struct Student s1, s2;
3. Accessing Members
- Use the dot operator (
.) to access members:s1.id = 101; strcpy(s1.name, "Alice"); s1.marks = 85.5;
4. Nested Structures
- A structure can contain another structure:
struct Date { int day, month, year; }; struct Student { int id; char name[20]; struct Date dob; };
5. Arrays of Structures
- Store multiple records in an array of structures:
struct Student students[5];
6. Pointers to Structures
- Use pointers with the arrow operator (
->):struct Student *ptr = &s1; printf("%d", ptr->id);
7. Advantages
- Organizes complex data in one unit
- Easier data management
- Supports modular programming
8. Limitations
- Cannot have operations directly on structures
- Memory allocation is static unless combined with pointers
Example Code
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[20];
float marks;
};
int main() {
struct Student s1;
s1.id = 101;
strcpy(s1.name, "Alice");
s1.marks = 88.5;
printf("ID: %d\nName: %s\nMarks: %.2f\n", s1.id, s1.name, s1.marks);
return 0;
}