Structures in C

C has a user defined datatype and Structure is one of them.
Syntax for creating a structure:
struct
{
datatype variable_1;
datatype variable_2;
};
The points to remember about structure are:
1.A structure is used in data structures for creation of node
2.The total size occupied by structure is sum of sizes occupied by each variable.
3.Accessing a variable in a structure is done using a dot '.' operator.\
4.If we need to access each variable using a address of a structure is by using '->' operator.
STRUCTURE CREATION:
struct my_structure
{
int my_variable;
char variable_name[12];
int sequence_number;
};
This is declaration of structure.
INITIALIZE A STRUCTURE:
struct my_structure definition;
definition.my_variable=10;
definition.variable_name[12]="Structure";
definition.sequence_number=1;
PRINT DATA IN A STRUCTURE
printf("%d is data in structure\n",definition.my_variable);
printf("%s is string in structure\n",definition.variable_name);
printf("%d is sequence number\n",definition.sequence_number);
printf("%d is size of structure",sizeof(definition));
The output of above snippet is
10 is data in structure
Structure is string in structure
1 is sequence number
13 is size of structure
UNION:
Union is also a user defined data type .
Creation of union syntax is
union
{
datatype variable_1;
datatype variable_2;
datatype variable_3;
};
A union variable is also accessed using a dot operator.
INITIALIZATION OF UNION
union union_name
{
int data=10;
char name[20]="union name";
};
DISPLAY DATA FROM A UNION
union union definition;
printf("%d is data in union\n",definition.my_variable);
printf("%s is string in union\n",definition.variable_name);
printf("%d is size of union",sizeof(definition));
The output of the above snippet is
10 is data in union
union name is string in union
10 is size of union
The only difference between a structure and a union is the memory space occupied by it .
1.Using structure the size is sum of sizes of each variable
2.By using a union total size occupied is maximum of sizes of all variables.
USING ADDRESS VARIABLE TO ACCESS DATA
struct my_structure *my_structure_2;
my_structure_2=&definition
printf("%d is data in structure\n",my_structure_2->my_variable);
printf("%s is string in structure\n",my_structure_2->variable_name);
printf("%d is sequence number\n",my_structure_2->sequence_number);
OUTPUT IS
10 is data in structure
Structure is string in structure
1 is sequence number
Same applies to union
HOPE THIS HELPS...............
HAPPY READING............