structure and union

Structure

  • A struct keyword is used to declare a structure in C .
  • The body of structure contains the definition of its members and each members must have a name.
struct<name>

{
member 1
member 2
:
member n
};
struct student
{
char name[20];
int age;
int roll;
char class[5];
};

Demonstration of Structure

#include<stdio.h>
#include<conio.h>
void main(){
struct student{
char name[20];
int age;
int roll;
char class[5];
};
struct student s1;
clrscr();
printf(“\n enter data of a student”);
gets(s1.name);
scanf(“%d%d%s”,&s1.age, &s1.roll, s1.class);
printf(“\n first student name , age, rollno, class is “);
printf(“%s\t%d\t%d\t%s\t”, s1.name, s1.age, s1.roll, s1.class);
getch();
}

Unions

  • unions is also derived data type like a structure.
  • union is used to store different members at same memory location.

Demonstration of unions

#include<stdio.h>
#include<conio.h>
void main(){
union id{
int size;
};
struct{
char naem[20];
float price;
union id desc;
}
shirt;
clrscr();
printf(“enter the data of shirt”);
printf(“name \n”);
gets(shirt.name);
printf(“Price:”);
scanf(“%f “,&shirt.price);
printf(“size:”);
scanf(“%d”,&shirt.desc.size);
printf(“the enterd data is”);
printf(“%s %f %d”, shirt, name, shirt.price, shirt.desc.size);
getch();
}