Structures and unions are user-defined data types that allow grouping of different types of data under a single name.
1. Structure
- Declaration:
struct Student {
int id;
char name[20];
float marks;
};
- Initialization:
struct Student s1 = {1, “Alice”, 85.5};
- Access members using dot operator (.):
printf(“%s”, s1.name);
2. Nested Structure
- Structure inside another structure.
struct Date {
int day, month, year;
};
struct Student {
char name[20];
struct Date dob;
};
3. Array of Structure
- Store multiple structure variables.
struct Student s[3];
s[0].id = 1;
4. Array within Structure
- Structure can have arrays as members.
struct Student {
char name[20];
int marks[5];
};
5. Passing Structure & Array of Structure to Functions
- By Value: Copies data; original structure unchanged.
- By Reference (using pointers): Allows modification of original data.
void printStudent(struct Student s);
void updateMarks(struct Student *s);
6. Structure & Pointer
- Access members using arrow operator (->).
struct Student *ptr = &s1;
printf(“%s”, ptr->name);
7. Bit Fields
- Allows storing data using a specific number of bits.
struct Flags {
unsigned int isAdmin:1;
unsigned int isGuest:1;
};
8. Union and Its Importance
- Union stores different types in the same memory location. Only one member can hold a value at a time.
union Data {
int i;
float f;
char c;
};
- Useful to save memory.
9. Structure vs Union
| Feature | Structure | Union |
| Memory | Separate for each member | Shared memory for all members |
| Access | All members simultaneously | Only one member at a time |
| Size | Sum of sizes of all members | Size of largest member |
| Use Case | Store different data together | Save memory when only one value is needed |
Key Takeaways
- Structures group different data types; unions share memory among members.
- Nested structures and arrays inside structures provide flexibility.
- Use pointers to structures for efficient function calls and memory access.
- Bit fields save memory by using specific bits for flags.
- Arrays of structures are useful for storing multiple records.
- Structure vs Union: choose union to save memory when only one value is needed.