Difference between structure, union,
and array
1. Structure (struct)
Definition:
A structure is a user-defined data type that groups variables of
different data types under one name.
Basic Concept:
Each member has its own separate memory.
Can store multiple values of different types.
Example:
struct Person {
char name[20];
int age;
float height;
};
This struct Person can hold a name, age, and height together.
Key Point:
Structure = Group of variables of different types, each with
separate memory.
2. Union
Definition:
A union is like a structure, but all members share the same memory
location.
Basic Concept:
Only one member can be used at a time.
Saves memory compared to structure.
Example:
union Data {
int i;
float f;
char str[20];
};
All variables (i, f, and str) share the same memory, so only one
should be used at a time.
Key Point:
Union = One memory for all members, used to store one value at a
time.
3. Array
Definition:
An array is a collection of elements of the same data type, stored in
contiguous memory locations.
Basic Concept:
Used to store multiple values of the same type.
Accessed using an index.
Example:
int numbers[5] = {1, 2, 3, 4, 5};
This is an array of 5 integers.
Key Point:
Array = Multiple values of the same type, accessed by index.
Summary Table:
Feature Structure Union Array
Data
Different Different Same
Types
Separate for each Shared among all Continuous for all
Memory
member members elements
All members at One member at a
Access By index
once time
Efficient memory
Complex objects Collections (e.g.,
Use Case use (e.g., variant
(e.g., student info) list of marks)
data)
Difference between Structure, Union and Array:
Feature Structure Union Array
Group variables Store multiple
Group variables of
Purpose of different values of same
different types
types type
All members
Each member has Each element has
Memory share same
its own memory its own memory
memory
Size = element
Sum of sizes of all Size of the
Size size × number of
members largest member
elements
All members can Only one
Elements accessed
Access be accessed at any member is valid
by index
time at a time
Built-in derived
Type User-defined User-defined
type
Saving data in
Example Storing info like Storing a list of
one format at a
use case ID, name, marks numbers or names
time