Structure and Union

Structure

Definition:- A Group of data items of different data types stored in continuous memory locations is known as a Structure.

struct:-  It is a keyword which is used to declare a structure.

Declaration of structure:

Form 1:-
struct struct_name
{
  data item-1;
  data item-2;
  ------------
  ------------
  data item-n;
};

Example:
struct emp
{
int eno;
char ename[80];
float sal;
};

Declaration of structure variable:- struct struct_name identifier;

      Example:-struct emp e;

Access operator:- (.)It is used to access the data items of the structure with the help of structure variable.

Example:-

e.eno;
e.ename;
e.sal;

Initialization:-struct struct_name identifier={val-1,val-2,…..val-n};

      Example:- struct emp e={100,”gouse”,10000};

Form 2: Declaration of struct and structure variable in a single statement
struct struct_name
{
  data item-1;
  data item-2;
  -----------
  ------------
  data item-n;
}var_list;

Example:

struct emp
{
int eno;
char ename[80];
float sal;
}e;

Initialization:
Example:
struct emp
{
int eno;
char ename[80];
float sal;
}e={100,”gouse”,10000};

Programs: Initializsation
#include<stdio.h>
#include<conio.h>
struct emp
{
  int eno;
  char ename[20];
  float sal;
}e={100,"SHISHIR",12000};
void main()
{
// struct emp e={100,"SHISHIR",12000};
  clrscr();
  printf("Size of structre :%d",sizeof(struct emp));
  printf("\nGiven employee number:%d",e.eno);
  printf("\nGiven employee name :%s",e.ename);
  printf("\nGiven employee salary:%f",e.sal);
  getch();
}
Program: Declaration: //26bytes(2 for int,1 for each character and 4 for float)
#include<stdio.h>
#include<conio.h>
struct emp
{
  int eno;
  char ename[20];
  float sal;
}e;
void main()
{
  // struct emp e;
  clrscr();
  printf("Size of structre :%d",sizeof(struct emp));
  printf("\nEnter employee number:");
  scanf("%d",&e.eno);
  printf("Enter employee name:");
   fflush(stdin);
  gets(e.ename);
  printf("Enter employee salary:");
  scanf("%f",&e.sal);
  printf("\nGiven employee number:%d",e.eno);
  printf("\nGiven employee name :%s",e.ename);
  printf("\nGiven employee salary:%f",e.sal);
  getch();
}

ARRAYS AND STRUCTURES

Like any other data type structure arrays can be defined. So that each array element can be of structure data type.                                      

    Example: Struct item it[100];

It defines an array called ‘it’, that contains of 100 elements. Each element is defined to be the type struct item.

Program:
#include<stdio.h>
#include<conio.h>
struct item
{
  int ino;
  char iname[20];
  float cost;
};
void main()
{
  struct item it[20];
  int n,i;
  float *f,f1;
  clrscr();
  f=&f1;
  *f=f1;
  printf("Enter no of records:");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    printf("Enter record%d:\n",i+1);
    printf("Enter item number:");
    scanf("%d",&it[i].ino);
    printf("Enter item name:");
   fflush(stdin);
   gets(it[i].iname);
   printf("Enter item cost:");
   scanf("%f",&it[i].cost);
  }
 clrscr();
  printf("\nGiven records:\n");
  printf("%-10s%-15s%s","INO","INAME","ICOST");
  printf("\n-------------------------------");
  for(i=0;i<n;i++)
  {
    printf("\n%-10d%-15s%.2f",it[i].ino,it[i].iname,it[i].cost);
  }
 getch();
}

STRUCTURES AND POINTERS

A pointer can also point to a structure for example…

Example:-
struct student
{
int sno;
char sname[80];
int m1,m2,m3;
};
struct student s;
struct student *p;

Here P is a pointer pointing student structure. Hence we can write p=&s;

   After making such an assignment, we can access every data item of student structure indirectly through p as follows.          

(*p).sno;

(p).sname; 
(p).m1;
(p).m2; 
(p).m3;

Here instead of writing ‘.’ and ‘*’ we use the structure pointer operator”arrow (->)”.Which is – and followed by > sign.

This means we can access every item of student structure through p as follows.

p->sno;
p->sname;
p->m1;
p->m2;
p->m3;

STRUCTURES WITH IN STRUCTURES (or) NESTED STRUCTURES

Form 1: Declaring a structure within another structure is called structure with in structure.

Example:-
struct student
{
int sno,c,cpp,unix;
char sname[20];
struct result
{
int tot;
float avg;
char res[20],div[20];
}r;
}s;

Accessing Data items:-
s.sno,s.c,s.cpp,s.unix,s.sname;
s.r.tot,s.r.avg,s.r.res,s.r.div;

Form 2: Declaring a structure variable with in another structure is called as structure within structure.

Example:
struct student
{
int sno,c,cpp,unix;
char sname[80];
};
struct result
{
struct student s;
int tot;
char res[20],div[20];
float avg;
}r;

Accessing Data items:
r.s.sno , r.s.c , r.s.cpp , r.s.unix , r.s.sname;
r.tot , r.avg , r.div , r.res;

UNIONS

UNION:-  A Union is similar to a struct, except it allows you define variables that shares  common storage space.     

Syntax:-
union union_name
{
  data item-1;
  data item-2;
  -----------
  -----------
  data item-n;
}var_list;
Program:
#include<stdio.h>
#include<conio.h>
struct test1
{
  int n;
  char ch;
  float ft;
}t1;
union test2
{
  int n;
  char ch;
  float ft;
}t2;
void main()
{
  clrscr();
  printf(“\nSize of struct:%d Bytes”,sizeof(t1));
  printf(“\nSize of Union:%d Bytes”,sizeof(t2));
  getch();
}

Differences Between Struct and Union:

   Structure                              Union
1. A Group of data items that belongs  to different data items.               

2. It allocates memory of all declared data items in it.                   

3. It access all data items at a time.
 
4. Each and every item has its own storage place.                        
1.It is also same as structure but the Only difference is memory allocation

2.It allocates memory of biggest data Item in it.

3.It can access only one item at a time

4.All items are shared common storage Place.

BIT-FIELDS:-

C permits to use small bit fields to hold data.

We have been using integer field of size 16 bits to store data. That data item requires much less than 16 bits of memory space.            

In such situations we waste memory space. At this situation we use small bit fields in structures.

  • The bit field data type is either int Or Unsigned int.
  • The largest value that can store integer bit field is 2power(n-1).
  • The largest value that can store unsigned integer bit field is 2power n  -1.
Declaration:-
struct struct_name
{
  int (or) unsigned identifier-1:bitlength;
  int (or) unsigned identifier-2:bitlength;
  -----------------------------------------
  -----------------------------------------
  int (or) unsigned identifier-n:bitlength;
  declaration of normal data items;
};

Example:-
struct emp
{
unsigned eno:7;
unsigned age:6;
char ename[80];
float sal;
};

NOTE:-The scanf function cannot read small bit fields. Because the scanf function scans and formats data into 2 bytes of address of the integer field.

Here is the important difference between structure and union:

StructureUnion
You can use a struct keyword to define a structure.You can use a union keyword to define a union.
Every member within structure is assigned a unique memory location.In union, a memory location is shared by all the data members.
Changing the value of one data member will not affect other data members in structure.Changing the value of one data member will change the value of other data members in union.
It enables you to initialize several members at once.It enables you to initialize only the first member of union.
The total size of the structure is the sum of the size of every data member.The total size of the union is the size of the largest data member.
It is mainly used for storing various data types.It is mainly used for storing one of the many data types that are available.
It occupies space for each and every member written in inner parameters.It occupies space for a member having the highest size written in inner parameters.
You can retrieve any member at a time.You can access one member at a time in the union.
It supports flexible array.It does not support a flexible array.

Advantages of structure

Here are pros/benefits for using structure:

  • Structures gather more than one piece of data about the same subject together in the same place.
  • It is helpful when you want to gather the data of similar data types and parameters like first name, last name, etc.
  • It is very easy to maintain as we can represent the whole record by using a single name.
  • In structure, we can pass complete set of records to any function using a single parameter.
  • You can use an array of structure to store more records with similar types.

Advantages of union

Here, are pros/benefits for using union:

  • It occupies less memory compared to structure.
  • When you use union, only the last variable can be directly accessed.
  • Union is used when you have to use the same memory location for two or more data members.
  • It enables you to hold data of only one data member.
  • Its allocated space is equal to maximum size of the data member.

Disadvantages of structure

Here are cons/drawbacks for using structure:

  • If the complexity of IT project goes beyond the limit, it becomes hard to manage.
  • Change of one data structure in a code necessitates changes at many other places. Therefore, the changes become hard to track.
  • Structure is slower because it requires storage space for all the data.
  • You can retrieve any member at a time in structure whereas you can access one member at a time in the union.
  • Structure occupies space for each and every member written in inner parameters while union occupies space for a member having the highest size written in inner parameters.
  • Structure supports flexible array. Union does not support a flexible array.

Disadvantages of union

Here, are cons/drawbacks for using union:

  • You can use only one union member at a time.
  • All the union variables cannot be initialized or used with varying values at a time.
  • Union assigns one common storage space for all its members.

KEY DIFFERENCES:

  • Every member within structure is assigned a unique memory location while in union a memory location is shared by all the data members.
  • Changing the value of one data member will not affect other data members in structure whereas changing the value of one data member will change the value of other data members in union.
  • Structure is mainly used for storing various data types while union is mainly used for storing one of the many data types.
  • In structure, you can retrieve any member at a time on the other hand in union, you can access one member at a time.
  • Structure supports flexible array while union does not support a flexible array.
Follow Us On