Untitled Document

Structures and Unions

Why do we need a structure?

We have seen till now that a variable can be of single data type either an int or float or char etc.
But if we want to store information consisting of different data types as a single entity then what do we do? Consider the example where we want to store the information of an employee of an organization and the employee details included employee number, employee name his address etc.
so C provides a data type called 'structure'.
A structure gathers together, different types of information that comprise a given entity.

A structure is a collection of one or more variable, possibly of different types grouped together under a single name for the convenience.


Syntax to declare a structure is:
struct name of the structure {
structure elements;
};


Example:
struct employee {
int emp_no;
char emp_name[25];
};


Once the structure data type has been defined one or more variables can be declared to be of that type.

For example the variables e1, e2, e3, e4 can be declared to be of the type struct employee as
struct employee e1,e2, e3,e4;

The above statement set aside 27 bytes of memory for each of the variable e1, e2, e3 and e4 as each of the variable need to store an integer value and a string i.e. two bytes for integer and a character array of 25 bytes.

Different ways of defining the structures and their variables
We can also combine definition of structure type and the declaration of the variables in one statement.

Example:
struct employee {
int emp_no;
char emp_name[25];
} e1, e2, e3, e4;
If we are combining definition of structure type and the declaration of the variables in one statement then we can even omit the name of the structure type.


Example:
struct{
int emp_no;
char emp_name[25];
} e1, e2, e3, e4;

Structure variables can also be initialized at the time of declaration.

Example:
struct employee {
int emp_no;
char emp_name[25];
} ; struct employee e1= { 101, "Krithika"};
struct employee e1= { 101, "Gokul"};

Example:
struct employee {
int emp_no;
char emp_name[25];
} e1, e2,e3= { 101, "Krithika"};

Note:
In the above example only the variable e3 is initialized.


We can even assign the value of one structure variable to another.
Example:
struct employee {
int emp_no;
char emp_name[25];
} e1, e2,e3= { 101, "Krithika"};
e2=e3;


Note:
  1. Semicolon must follow the closing brace of the structure type definition
  2. A structure type defines only the form of a structure and compiler will not reserve any space in memory

Accessing the structure elements: To access the elements of structure dot operator is used along with the structure variable.

Example:
e1.emp_no;
e1.emp_name;
Whatever be the elements of a structure, they are always stored in contiguous memory locations.


The example given reads the elements of the structure and displays the elements.
#include <stdio.h>
main ( )
{
struct employee
{
int emp_no;
char emp_name [25];
};
struct employee e1;
printf ("Enter the Employee number and name\n");
scanf ("%d%s",&e1.emp_no,&e1.emp_name);
printf("Employee Number is %d and Name is %s\n",e1.emp_no, e1.emp_name);
}


Output:


One structure can be nested within another structure:
A structure can be the element of another structure, which is given in the example.


Example:
struct empdt
{
char emphname [10];
int hnum;
};
struct employee
{
char empname [25];
int empno;
struct empdt empad;
} e1;


Program to read in the values for the employee details and display the read in values.
# include<stdio.h>
# include<conio.h>
main ( )
{
struct empdt
{
char emphname[10];
int hnum;
};
struct employee
{
char empname [25];
int empno;
struct empdt empad;
}e1;
printf ("\nEnter the name, number, housename and number\n\n");
scanf("%s%d%s%d",&e1.empname,&e1.empno,&e1.empad.emphname, &e1.empad.hnum);
printf("\n\nEntered details of employee\n\n");
printf ("Employee Name = %s\n",e1.empname);
printf ("Employee Number = %d\n",e1.empno);
printf ("Employee House Name = %s\n",e1.empad.emphname);
printf ("Employee House Number = %d\n",e1.empad.hnum);
}


Output:



Array of Structures:
Structures can be stored in the array when there are more number of records or structures to be stored.


Example:
# include<stdio.h>
# include<conio.h>
main ( )
{
struct empdt
{
char emphname[10];
int hnum;
};
struct employee
{
char empname [25];
int empno ;
struct empdt empad;
}e1[25];
int i,n;
clrscr();
printf("Enter the number of records you want to input\n\n");
scanf("%d",&n);
printf("Enter %d number of records\n\n",n);
printf ("\nEnter the name, number, housename and number\n\n");
for(i=0;i< n; i++)
{
scanf("%s%d%s%d",&e1[i].empname,&e1[i].empno,&e1[i].empad.emphname,&e 1[i].empad.hnum);
}
printf("\n\nEntered details of employee\n\n");
for (i=0; i<n;i++)
{
printf ("Employee Name = %s\n",e1[i].empname);
printf ("Employee Number = %d\n",e1[i].empno);
printf ("Employee House Name = %s\n",e1[i].empad.emphname);
printf ("Employee House Number = %d\n",e1[i].empad.hnum);
}
getch();
}


Output:


In the above program, in memory, compiler reserves space for two structures of type employee.


Passing Structures To Function:
Like an ordinary variable, a structure variable can also be passed to function. We may either pass individual structure element or entire structure at a time.
Program to pass individual structure element to the function.

#include<stdio.h>
# include<conio.h>
main ()
{
void disp1(char *, int);
void disp2(char *, int *);
struct employee
{
char empname[25];
int empno;
};
struct employee a;
clrscr();
printf("\nEnter the Name and Number\n\n");
scanf("%s%d",&a.empname,&a.empno);
disp1(a.empname,a.empno);
disp2(a.empname,&a.empno);
getch();
}
void disp1(s,t)
char *s;
int t;
{
printf("\nEntered details are\n\n");
printf ("Employee Name = %s Number = %d\n", s, t);
}
void disp2(s,t)
char *s;
int *t;
{
printf("\nEntered details are\n\n");
printf ("Employee Name = %s Number = %d\n", s, *t);
}


Output:



To the function disp1() Employee name (empname) is passed by the method call by reference and Employee number (empno) is passed by the method call by value.
To the function disp2() both Employee name (empname) and Employee number (empno) is passed by the method call by reference.


Note:
When you write a.empname, we get the base address of the array variable empname, so naturally it is call by reference in the calls for disp1() and disp()2.

#include<stdio.h>
# include<conio.h>
struct employee
{
char empname[25];
int empno;
};
main ()
{
struct employee a;
void disp1(struct employee);
clrscr();
printf("\nEnter the Name and Number\n\n");
scanf("%s%d",&a.empname,&a.empno);
disp1(a);
getch();
}
void disp1(e)
struct employee e;
{
printf("\nEntered details are\n\n");
printf ("Employee Name = %s Number = %d\n",e.empname,e.empno);
}


Output:



Note:
Structure is defined outside the main so that it will be available to the entire program i.e. to main and to the function disp1().


Structure Pointers:
The pointer pointing to a structure is called as structure pointer. It is like we have a pointer pointing to an int or a pointer pointing to a char or a pointer pointing to a float. Likewise, we have a pointer pointing to a structure. The example demonstrates the use of structure pointers.

# include<stdio.h>
#include<conio.h>
struct employee
{
char empname [25];
int empno;
};
main ()
{
struct employee a, *ptr;
ptr = &a;
printf ("Enter the empname & empno\n");
scanf("%s %d", &a.empname, &a.empno);
printf("Employee name%s Employee number%d\n",ptr->empname, ptr->empno);
getch ( );
}


Output:



To pass a structure variable to a function by referenc:
# include<stdio.h>
# include <conio.h>
struct employee
{
char empname[25];
int empno;
};
main ( )
{
void disp (struct employee *);
struct employee a;
printf ("Enter empname and empno\n");
scanf ("%s %d", &a.empname, &a.empno);
disp (&a);
getch();
}
void disp (ptr)
struct employee *ptr;
{
printf("Employee name is %s \n", ptr->empname);
printf ("Employee number is %d\n",ptr->empno);
}


Output:


The address of the structure variable a is passed to the function disp().

Self Referential Structures -
This is a structure in which one member is a pointer to the parent structure type.


Syntax :
struct tag
{
member 1;
member 2;
:
:
struct tag *next;
};

Where *next is the pointer variable. Thus, the structure of type tag will contain a member that points to another structure of type tag. Such structures are known as self-referential structures.


Example:
struct employee
{
char empname [25];
int empno;
struct employee *next;
};


Note:
These kinds of structures are used to create data structures like linked lists, stacks, queues etc.

UNIONS:
Similar to structures unions contain members which may have different datatype. But the difference is that all the members share the same storage area within the memory of the computer. br>Where as in structures each of the members are allocated a separate storage area within the memory.

Thus unions are used to conserve the memory.
There may be applications in which all the data members may not be used at a given point of timei.e. all the data members are not assigned the values.
In such cases instead of using Structures, Unions are used.


Syntax to declare a union:
union tag {
data member1;
data member2;
. data membern;
};


Syntax to declare a variable:
union tag variable1, variable2, varibale3...variablen;


Example:
union id{
char make[15];
int size;
};


A union can be embedded within a structure as shown below:
union id{
char make[15];
int size;
};
struct wear{
char color[15];
int price;
union id details;
};
struct wear shirt;


/* Program to demonstrate the use of union*/
#include<stdio.h>
#include<conio.h>
void main()
{
union id{
char make[15];
int size;
};
struct wear{
char color[15];
int price;
union id detai ls;
};
struct wear shirt;
printf("Enter Color, Make, Cost and Size of the shirt\n");
scanf("%s%s%d%d",&shirt.color,&shirt.details.make,&shirt.price,&shirt.details.size);
printf("Color: %s, Cost: %d,",shirt.color,shirt.price);
printf(" Make: %s, Size: %d\n",shirt.details.make,shirt.details.size);
printf("Enter Make\n");
scanf("%s",&shirt.details.make);
printf("Color: %s, Cost: %d,",shirt.color,shirt.price);
printf(" Make: %s Size: %d\n",shirt.details.make,shirt.details.size);
getch();
}


Output:



By looking at the output of the program we can make out that at a given point of time only one field of the union can have the value.
As seen in the above example although the value for make and size were given only the value of size is displayed correctly and we got garbage value for the make.
But next time when the value for make was given, value of correct value for make is displayed but for size we got garbage value.
Thus either the union field make will have correct value or size will have correct value but not the both.
Most recently used union field will retain the value.



Pointers << Previous     Next >>Dynamic Memory Allocation

Our aim is to provide information to the knowledge seekers.

Support us generously

comments powered by Disqus
Footer1