Structures and Unions
Structures and unions! These are fundamental data types in C that help in managing and organizing data efficiently.
Structures (Structs)
Structures allow you to group different types of data into a single unit. This is useful for representing complex data.
Declaration and Definition
To define a structure, use the struct
keyword followed by the structure name and the body containing the members.
Explanation:
Structure Definition:
struct Person
defines a structure withname
,age
, andheight
.Access Members: Use the dot operator
.
to access members of a structure.
Dynamic Allocation with Structures
You can also dynamically allocate memory for structures using pointers.
Explanation:
malloc
allocates memory for the structure.Use
->
to access members of a structure via a pointer.free
releases the allocated memory.
Unions
Unions are similar to structures but differ in how they manage memory. A union allows different data types to share the same memory location.
Declaration and Definition
To define a union, use the union
keyword followed by the union name and its members.
Explanation:
Memory Sharing: All members of a union share the same memory location. Changing one member affects the others.
Size: The size of a union is determined by the size of its largest member.
Comparison: Structures vs. Unions
Structures: Each member has its own memory location. Size is the sum of sizes of all members.
Unions: All members share the same memory location. Size is the size of the largest member.
Using Structures and Unions
Structures: Ideal for cases where you need to group data but keep them distinct.
Unions: Useful when you need to store different types of data but only one at a time.
Example: Combining Structures and Unions
Explanation:
Combining: A
struct
can contain aunion
to allow different types of data in the same structure.
Summary
Structures group different data types into a single unit.
Unions allow different data types to share the same memory location, useful for memory-efficient storage when only one type is needed at a time.
Dynamic Allocation for structures allows flexible memory management.
Combining structures and unions can be powerful for complex data representations.
Last updated
Was this helpful?