Structure
The collection of dissimilar data or heterogeneous data items treated as single unit. Each
data item is called member of structure. The keyword struct is used to declare structure
variable and type of structure variable is defined by the tag name of the structure.
Structures are one of the ways to create a custom data type in C. Defining the structure
Used to specify what data are included within structure. It gives information about
members such as number, types and order.
syntax
struct structure_name/tag_name
{
data_type member_variable1;
data_type member_variable2;
.........................................
data_type member_variableN;
};
Example of structure definition:
struct student
{
int roll;
char name[30];
char address[30];
};
Union
Unions are similar to structure in the sense that they are also used to group together
members of different data types. The distinction lies in the fact that all members within a
union share the same memory space whereas each member within a structure is allocated
a unique memory space.
syntax
union union_name{
data_type member _variable1;
data_type member_variable2;
..................................
data_type member_variableN;
};
Once union_name is declared as new data type, then variables of that type
can be declared as
union union _name union _variable;
Example
union student
{
int roll_no;
char name[20];
float marks;
};
Structure vs union