Defining structures and unions
Defining Structures and Unions A structure is a collection of variables enclosed within a specific memory location. These variables share the same memory...
Defining Structures and Unions A structure is a collection of variables enclosed within a specific memory location. These variables share the same memory...
A structure is a collection of variables enclosed within a specific memory location. These variables share the same memory space, and can be accessed directly using an identifier. Structures can contain both fixed-size variables and dynamically-sized variables.
struct student {
char name[50];
int age;
float marks;
};
Union is a data type that combines multiple data types into a single variable. This means a single variable can store values of multiple types, without the need for separate variables.
union data_type {
int i;
float f;
char c;
};
Key differences between structures and unions:
Structure:
Variables are allocated memory in a single contiguous block.
Each variable has a specific memory address.
Structures can contain multiple data types.
Union:
Variables are allocated memory in a single memory location.
Only one variable can be stored at a time.
Unions only contain data of the same type.
Examples:
A structure can be used to store student information, such as name, age, and marks.
A union can be used to store a student's ID, name, and email.
Benefits of using structures and unions:
Efficiency: Structures and unions can be used to optimize memory usage and access.
Data sharing: Structures and unions allow multiple variables to be accessed using a single identifier.
Type safety: Unions ensure that variables are of the same type, preventing type errors