structures and unions in C

Structures and Unions in C :
We used to use Unions when we were shot on memory , but then we got advanced in terms of storage and hence we shifted to structures which are more flexible .

Structures in C
A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member.

Union
A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure.

Do watch the following video before starting the coding part :

/* write a program to store and print the roll number , name and age o
a student using structures(with and without pointer) and union
*/
#include<stdio.h>
#include<stdlib.h>
struct student
{
int roll_no;
char name[30];
int age;
int marks;
};
//_________________
struct person
{
int age;
float weight;
char name[30];
};
//_________________
union employee
{
int id;
int age;
int work_years;
char name[10];
};
int main()
{
//without pointer
struct student p1 = {9,"NIRA",14,78};
printf("%d %s %d %d \n",p1.roll_no,p1.name,p1.age,p1.marks);
printf("size of the structure student is %d",sizeof(student));
//_________________________________________________________________
//with pointer
//now one thing to note that the dot operator will not work.
//as p2 is of type pointer so --> will work now.
struct person *ptr;
ptr = (struct person*)malloc(sizeof(struct person));
   for(int i = 0; i < 2; ++i)
   {
       printf("\nEnter name, age and weight of the person respectively:\n");
       scanf("%s%d%f", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight);
   }

//ptr-->age = 10 , or ptr.age = 10 does not work
printf("Displaying Infromation:\n");
   for(int j= 0; j < 2; ++j)
       printf("%s\t%d\t%.2f\n", (ptr+j)->name, (ptr+j)->age, (ptr+j)->weight);
//the above shows that both the concept that the pointer and direct implementation works
//____________________________________________________________________
struct inside_the_main
{
int yes;
}p;
p.yes =0;
//hence we can even define the stucture inside the main function
//_____________________________________________________________________
union employee test;
test.id =10;
test.age =33;
test.work_years =10;
printf("%d",sizeof(test));
printf("\nsize of the union is %d\n",sizeof(test));
scanf("%d",&(test.name));
printf("size of the union is %d",sizeof(test));
return 0;
}

Comments

Popular Posts