Chapter 10 Structure and Unions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Ganesh K.

Sethi, Multani Mal Modi College, Patiala -1-

STRUCTURES AND UNIONS


Need of Structure and Unions: So far, we have been using either simple variables or arrays in different
programs of the previous chapters. Although these two data types are capable of handling a number of
problems, yet they have certain drawbacks. Simple variable can handle only one value at a time and
arrays can process a number of homogeneous values at a time. But, if we want to represent a collection of
data items of different types using a single name then we cannot use an array. For that purpose, C has a
user defined data type known as structure.
A structure is a collection of related items of different data types. For example, a structure can be used
to represent a set of attributes of a student such as name (a character array), roll number (an integer),
marks (an integer) and height (a floating point number).
Structure Declaration: A structure declaration creates a format that may be used to declare structure
variables. Consider a student database consisting of student‟s name, address, roll number, age and
percentage of marks. We can define a structure to hold this information as follows:
struct student
{
char name[30] ;
char address[100] ;
int rollno ;
int age ;
float percentage ;
}
The keyword struct declares a structure to hold the details of five fields, namely name, address, rollno,
age and percentage. These fields are called structure elements or members. Each member may belong to a
different type of data. Here, „student‟ is the name of the structure and is called the structure tag. It gives a
name to the structure being defined. The tag name may be used subsequently to declare variables that
have the tag‟s structure. The portion of the structure definition enclosed in braces is known as a structure
template. The syntax for declaring a structure is as follows:
struct tag_name
{
data_type member1 ;
data_type member2 ;
................................
................................
};
The above declaration has not declared any variable and no memory is set aside for this
structure. Note that the members of a structure themselves are not variables. So, they do not occupy any
Ganesh K. Sethi, Multani Mal Modi College, Patiala -2-

memory until they are associated with the structure variables. The general syntax of declaring structure
type variables is as follows:
struct tag_name svar1, svar2, ........svarn ;
e.g. struct student student1, student2 ;
Here, student1, student2 are structure type variables whose structure is given by student. It is also
possible to combine both the template declaration and variables declaration in one statement. Consider
an example:
struct employee
{
char emp_no[5] ;
char name [20] ;
float salary ;
} emp1, emp2, emp3 ;
Generally, structure definitions appear at the beginning of the program file, before any
variables or functions are defined. They may also appear before the main. In such cases, the definition is
global and can be used by other functions as well.
Structure Initialization: Like any other data type, a structure variable can be initialized at the time of
declaration. The format used is quite similar to the initialization of arrays. Consider the following
example:
struct student
{
char name[20] ;
int age ;
float avg ;
};
struct student st1 = {“Sabhya”, 5, 805} ;
Here, st1 is a structure type variable, which is assigned some initial values at the time of
declaration. Some more variations are also possible in initializing a structure type variable.
Following set of statements are also valid for initializing structure variables:
(i) struct student
{
char name[20] ;
int age ;
float avg ;
} st1 = {“Sabhya”, 5, 805} ;
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.
Ganesh K. Sethi, Multani Mal Modi College, Patiala -3-

Storage of Structures: When a structure data type is declared in a program then memory is not
allocated to it. Memory is allocated only, when a structured variable is declared. The members of a
structure variable are stored in consecutive memory locations. The total memory allocated to a structure
variable is equal to the sum of memory allocated for the individual members of that structure. Each
member of structure variable is allocated memory in order of their respective declarations inside
structure template. Consider the following example:
struct employee
{
int code ;
char name [20] ;
float salary ;
}x;
Here x is a structure variable, whose members will be stored in a block of 26 consecutive
memory locations. The different members of x will be stored in memory in the following way:
xcode xname xsalary

1000 1002 1022 1026


| 2 Bytes 20 Bytes 4 Bytes
Accessing Structure Members: Once a structure variable is declared, its members can be accessed
using dot operator (). This operator is also known as member operator or period operator. The syntax for
accessing members of a structure using dot operator is:
st_var.member
where st_var is structure variable and „member‟ is the name of the member to be accessed. For example,
book1.price will access the price of book1 and can be treated like any other ordinary variable. The
following example illustrates the use of dot operator to read and write details of two students:
struct student
{
char name[20] ;
int age ;
float avg ;
};
main( )
{
struct student st1, st2;
printf(“Enter data for first student:\n”) ;
scanf(“%s %d %f ”, st1.name, &st1.age, &st1.avg) ;
printf(“Enter data for second student:\n”) ;
Ganesh K. Sethi, Multani Mal Modi College, Patiala -4-

scanf(“%s %d %f ”, st2.name, &st2.age, &st2.avg) ;


printf(“\n The details of students is :\n”) ;
printf(“%s %d %f \n”, st1.name, st1.age, st1.avg) ;
printf(“%s %d %f ”, st2.name, st2.age, st2.avg) ;
getche( ) ;
}
Array of Structures: An array of structure refers to an array, whose every element is a structure of the
same type. Thus, instead of declaring 10 different structure variables, we can declare an array of structure
having 10 elements. An array of structure is an array of similar data type, whereas every element of such
array is a collection of different data types. Suppose, we want to store and process information of 50
students of a college then we can declare an array of structure in the following way:
struct result
{
int sub1 ;
int sub2 ;
int sub3 ;
};
struct result student [50] ;
Note that, student is an array of structure having 50 elements in it and every element of
such array is a collection of sub1, sub2 and sub3. Individual elements of a structure in an array of
structures are accessed by referring to structure variable name, followed by subscript, followed by dot
operator and ending with the structure element desired. Suppose we want to access the marks in sub1 of
6th student, we can do so by writing
student[5].sub1 ;
An array of structures is stored inside the memory in the same way as a multi-dimensional
array.
Example: Write a program to calculate the total marks obtained by n students in a class using array of
structures.
Solution:
#include <stdio.h>
struct marks
{
int sub1 ;
int sub2 ;
int sub3 ;
};
main ( )
{
struct marks student [100] ;
int n, i, total ;
Ganesh K. Sethi, Multani Mal Modi College, Patiala -5-

printf(“How many students in class ?”)


scanf(“%d”, &n) ;
for(i = 0 ; i < n ; i ++)
{
scanf (“%d %d %d”, &student[i]. sub1, &student[i].sub2,&student[i]. sub3) ;
total = student[i].sub1+student[i].sub2+student [i].sub3;
printf(“Marks of student no. %d is %d\n”, i+1, total) ;
}
getch ( ) ;
}
Arrays within Structures
We can also use arrays as structure members. C permits the use of single or
multidimensional arrays as members of a structure. For example, the following structure declaration is
valid:
struct marks
{
int rollno ;
int sub[3] ;
} student[50] ;
Here, the member „sub‟ contains three elements, sub [0], sub [1] and sub [2]. These elements
can be accessed by using appropriate subscripts.
Example: Write a program to calculate total of marks obtained in three subjects by each student in a class
of n students by using array within structures.
Solution:
struct marks
{
int rollno ;
int sub[3] ;
} student[50] ;
main( )
{
int i, n, total = 0, j ;
printf(“How many students in class ?”) ;
scanf(“%d”, &n) ;
for (i = 0 ; i<n ; i++)
{
Ganesh K. Sethi, Multani Mal Modi College, Patiala -6-

printf(“Enter Rollno. \n”) ;


scanf(“%d”, &student[i]. rollno) ;
printf(“Enter marks in three subjects\n”) ;
for( j = 0 ; j<3 ; j ++)
{
scanf (“%d”, &student[i].sub[ j]) ;
total = total + student [i].sub [ j] ;
}
printf(“Total marks of Roll No. %d is %d \ n”, student [i].rollno, total) ;
total = 0 ;
}
getch( ) ;
}
Difference between arrays and structures
As we have seen in the previous section, arrays can be used as members of a structure. We can also use
an array of structure in a program. In spite of all these uses, arrays are different from structures in the
following aspects:

Array Structure
(i) An array is a collection of data items of (i) A structure is a collection of data items
homogeneous data type i.e. of same of heterogeneous data types i.e. of
type. different types.
(ii) It has declaration only. (ii) It has declaration and definition.
(iii) There is no keyword in using arrays. (iii) The keyword struct is used.
(iv) An array name represents the address of (iv) A structure name is known as tag. It is a
the starting element. short hand notation of the declaration. It
does not represent the address of the
starting element.
(v) An array cannot have bit fields. (v) A structure may contain bit fields.

Unions: Unions, like structures, are also used to group a number of variables of different types in a
single unit. However, there is a major difference between them in terms of storage. Each member within a
structure has its own unique storage area, whereas all members of union share the same storage area
within the computer‟s memory. The compiler allocates sufficient memory to hold the largest member
type in the union. Since all the members of union occupy the same memory location, the value of the
previous member will be destroyed, when a value is assigned to another member of the union.
Ganesh K. Sethi, Multani Mal Modi College, Patiala -7-

(i) Union Declaration: The syntax for declaring a union and declaring variables of union type are same
except that instead of struct keyword, union keyword is used. Consider the following declaration of
union:
union sample
{
int i ;
float f ;
char c ;
} s1 ;
Here, sample is the name of the union and it has three data members i, f and c; s1 is declared
as union variable of type sample. In the above example, the compiler allocates a block of four consecutive
bytes sufficient enough to hold the largest data item as specified in the union. Out of three data members
i, f and c, only one member can be stored at a time. When i is assigned some value, it will be stored in first
two bytes, the other two bytes will be unused.
Similarly c will be stored in first byte and f will be stored in all four bytes of the block. The
sharing of a block of four consecutive memory locations by all members of a union is shown in the
following figure:
1201 1202 1203 1204

i
f

A union may be a member of a structure and a structure may be a member of a union.


(ii) Initialization of Union: Initialization of a union is different from the initialization of a structure. Since
all the members of the union occupy the same storage space required for the largest member of the union,
only one member of the union can be initialized at a time. The limited initialization has a little practical
value in processing a union.
(iii) Processing of Union: Processing of unions is complex as compared to the processing of structures,
because at a time we can store only one data member of union. Care must be taken to access only that
member of union, which is currently stored in common memory block.
An attempt to access a data member that is not currently stored, will give unpredictable
results. An individual union member can be accessed in the same way as an individual structure member
using dot operator. The following program illustrates the processing of unions.
Example:
main( )
{
Ganesh K. Sethi, Multani Mal Modi College, Patiala -8-

union
{
char color ;
int size ;
} shirt ;
printf(“Memory requirement of union is %d bytes\n”, size of (shirt)) ;
shirt.color = „b‟ ;
printf(“Color of shirt is %c\n”, shirt.color) ;
printf(“Size of shirt is %d\n”, shirt.size) ;
shirt.size = 40 ;
printf(“Size of shirt is %d\n”, shirt.size) ;
getche( ) ;
}
Execution of the above program results in the following output:
Memory requirement of union is 2 bytes
Color of shirt is b
Size of shirt is 28002
Size of shirt is 40
The third line of the output gives some garbage value, because we are trying to access
that union member which is not currently stored. The „sizeof‟ operator is giving the size of union in terms
of bytes. Here, the largest data item of union is of int type, so „sizeof‟ returns 2.
(iv) Applications of Union: Unions are used to conserve memory economically. They are useful for
those applications in which a grouped data item has a number of members and values are not
assigned to all members simultaneously.
(v) Difference between structure and union:
Structure Union
(i) Every member of a strcuture has its (i) All members of a union share the same
own memory. memory.
(ii) Keyword struct is used. (ii) Keyword union is used.
(iii) All members of a structure may be (iii) At a time, only one member of a union
given some initial values may be initialized.
simultaneously.
(iv) Different interpretations of the same (iv) Different interpretations for the same
memory location are not possible. memory location are possible.
(v) It consumes more memory space as (v) Memory is consumed economically.
compared to union.
Ganesh K. Sethi, Multani Mal Modi College, Patiala -9-

You might also like