You are on page 1of 33

Structure and Union

STRUCTURES
6.1.1. Introduction
^ ^,fmCtUre is a User defined data type- A structure is a combination of several erent previously
defined data types, including other structures we have defined
> A structure is a grouping of related data in a way convenient to the programmer or
user of the program.
> A structure is a collection of variables of different types. Structures are sometimes
referred to as Abstract Data Types, (ADTs).
> Variables in a struct are called members or fields, and are accessed by their
J
name.
> The size of a structure is the sum of the sizes of all the variables it holds The
assignment operator with the structure declaration can not be used
A structure is a convenient method of handling a group of related data items of
different data types.

6.1.2. Difference between Structures and Arravs


Array 1 Structure
Data Collection
Array is a collection of Structure is a collection of heterogeneous
homogeneous data. data.
Element Reference
Array elements are referred by Structure elements are referred by its
subscript. 5 unique name.
Access Method
Array elements are accessed by Structure elements are accessed by its
it’s position or subscript. object as V operator.
Data type
Array is a derived data type. | Structure is user defined data type
Syntax
struct struct_name {
structure member 1; structure member 2;

structure member n;
}struct_var_nm;
F.-xamnle ----------------------------------------------------------- --------------------------
int mo [5]; struct item_mst {
int mo;
char nm[50];
lit; —■ ----------------

6.1.3. Definition and Declaring Structure Variables


> A structure is a collection of variables under a single name. These variables can be
of different types, and each has a name which is used to select it from the structure.
> Structures are commonly used to define records which will be stored in tiles.
Pointers and structures facilitate the formation of more complex data structures
such as linked lists, queues, stacks and trees.
> Declaring a structure requires Ihe struct keyword, followed by a name. Then
collection of variables is declared between a pair of curly brackets.
Syntax:
struct struct_name
{
type member 1; type member2;
}; .
> Structure declaration always starts with struct keyword. Here, struct_name is
known as tag. The struct declaration is enclosed within a pair of curly braces.
> Using struct and tag user can declare structure members like member 1, member2
and so on. These are the members of the structure. Variables of the corresponding
data type are created as given below:
struct struct_name ml, m2;
Here, ml, m2 are variables of structure struct_name.
> The declaration defines the structure but this process doesn’t allocate memory. The
memory allocation takes places only when variables are declared. For example,
consider the student structure specifier is illustrate in figure below,
Keyword
j Structure name

struct Student {
int Rollno;
int Subject, I Brackets delimit gtnlcture members declaration float Marks; '
); structure members
In this example,
Rollno 2 bytes
Subject 2 bytes
Marks 4 bytes
Student structure will take total 8 bytes in the memory.
6.1.4. Variables Initialization
All external and static variables, including structures, which are not explicitly
initialised by the programmer, are automatically initialised by the system to zero.
In traditional C, only external and static variables can be initialised. ANSI C allows
automatic variables, including structures, to be initialised as well.
The syntax for initialising structures is similar to that for initialising arrays. A structure
variable in a declaration can be initialised by following it with an equal sign and a list
of constants contained within braces. If not enough values are used to assign all the
members of the structure, the remaining members are assigned the value zero by
default. Some examples are:
1) Card c = {13, ‘h’}; /* the king of hearts */
2) Complex a[3][3] = {
{{1.0,-0.1}, {2.0, 0.2}, {3.0, 0.3}},
{{4.0,-0.4}, {5.0, 0.5}, {6.0, 0.6}}, .
}; /* a[2][] is assigned zeroes */
3) struct fruit frt = {“plum”, 150};
4) struct home_address {
char * street; char
*city_and_state; long
zip_code;
} address = {“87 West Street”, “Aspen, Colorado”, 80526};
5) struct home_address previous_address = {0};
The last example illustrates a convenient way to initialise all members of a structure to
have value zero. It causes pointer members to be initialised with the pointer value
NULL and array members to have their elements initialised to zero.
Rules for Initializing Structures
1) We cannot initialize individual members inside the structure template.
2) The order of values enclosed in braces must match the order of members in the
structure definition.
3) It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining blank. The uninitialized members should be only
at the end of the list.
4) The uninitialized members will be assigned default values as follows:
i) Zero for integer and floating point numbers.
ii) ‘\0’ for characters and strings.

6.1.5. Accessing Members


Each element in a structure can be accessed and manipulated using operators and
expressions. The C language uses hierarchical naming conventions that first use the
structure variable-identifier and the element-identifier.
Syntax
variable_identif!er.element-identif!er;
Or,
structure_var.member_variable;
The structure variable-identifier is separated from element-identifier by a dot (.)• The
dot here is known as the direct selection operator, which is a postfix operator at
precedence level 1 in the precedence table.
For example, consider the following statement
part2. modelnumer=3884;

The first component of above expression involving the dot operator is the name of the
specific structure variable(part2), not the name of the structure definition(part).

The variable name must be used to distinguish one variable from another, such as parti,
part2 and so on, as shown in figure 6.1.

Program 1: Illustrating structure.


#include <stdio.h>
#include <conio.h>
struct student} char
id_num[6]; char
name[ll]; char
gender; int age;
}:
int main(void)
{
struct student studno_l;
// studno_l.id_num = "A3214"; //Illegal, const char to char[]
// studno_l.name = "Smith"; //Illegal, const char to char[]
*• ~ clrscr();
- printf("First of all, get the size of the struct: %d\n", sizeof(struct
student));
printf("Enter student ID num (5 max): ");
// scanf( %s , studno_ 1 ,id_num); // unsecure version scanf("%s",
studno_l.id_num); printf("Enter student name (10 max): ");
// scanf( %s , studno_l.name); // old, unsecure version
scanf("%s", studno_l.name);
studno_l. gender = 'M'; studno_l.age = 30;
printf("\n ------ ------------\n");
printf("ID number: %s\n", studno_l.id_num); printf("Name :
%s\n", studno_l.name); printf("Gender : %c\n", studno_l.gender);
printf("Age : %d\n", studno_l.age);
printf(" ------------------- \n");
getch();
}
Output

Program 2: To calculate the student-wise totals and store them as a part of the
structure.
#include <stdio.h>
#include <conio.h>

struct marks {
int subl; int sub2;
The structure variable-identifier is separated from element-identifier by a dot (.). The dot
here is known as the direct selection operator, which is a postfix operator at
precedence level 1 in the precedence table.
For example, consider the following statement
part2.modelnumer=3884;

The first component of above expression involving the dot operator is the name of the
specific structure variable(part2), not the name of the structure definition(part).

The variable name must be used to distinguish one variable from another, such as parti,
part2 and so on, as shown in figure 6.1.

y modelnumber ^

partnumber

pnce

^ modelnumber y

partnumber

^ modelnumber ^

partnumber

part2. modelnumber

Figure 6.1: Dot

Operator

Program 1: Illustrating structure.


#include <stdio.h>
#include <conio.h>
struct student} char
id_num[6J; char
name[ll]; char
gender; int age;
}:
mt sub3; int
total;
};
void main()
{
int i;
struct marks student[3]={ {45, 67, 81, 0},
{75, 53, 69,0},
, {57,36,71,0}};
struc^marks total; clrsciO;
for(i=0;i<=2;i++)
student[i].total=student[i].subl+student[i].sub2+student[i].sub3;
total. sub 1 =total. sub 1+student [i]. sub
1; total. sub2=total. sub2+student[i].
sub2;
total.sub3=total.sub3+student[i].sub3;
total.total=total.total+student[i] .total;
}
printf(" STUDENT TOTAL\n\n");
for(i=0;i<=2;i++)
printf("Student [%d] %d\n", i+l,student[i].total); getch();

Explanation: In the program, a four-member structure is declared, the fourth one for
keeping the student-totals.
Note: A member name can be any valid C name and can be the same as an existing
structure variable name.

6.1.6. Structure Operation


A structure is an entity that can be treated as a whole. There is only one operation that
can be performed on the structure as a whole - a structure can be copied into another
structure of the same type using the assignment operator.
Comparing structures in c is not permitted to check or compare directly with logical
operators. Only structure members can be comparable with logical operator. Such as,
struc_object_l.age = = struc_object_2.age.
For example, consider the following program to illustrate the comparison of members
in a structure
Program 3: Illustrating comparison of member in a structure.
#include <stdio.h>
#include <conio.h> struct student { int mo;
char name[20]; int percentage;
};
main(){
//compare structure via members
struct student stul = {1001,"pravesh",87}; struct student stu2 =
{1002,"Abhay",85};

if (stul.percentage < stu2.percentage){ printf("%s has higher


marks.",stu2.name);
}
else {
printf("%s has higher marks.",stul.name);
}
getch();

Output __________ __________

Program 4: Illustrating comparison of member in a structure.


#include <stdio.h>
li
S
m
#include <conio.h> struct class {
int number; char name[30]; float marks;
};
main()
{
int y;
struct class studentl = {01, "pravesh", 88.50}; struct class student2 = {02, "Abahay",
76.00}; struct class student3; student3 = student2;
y=((student3.numben=student2.number)&&(student3.marks=student2.marks))‘>
1:0;
if(y ==D ' .
printf("student2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number, student3.name, student3.marks);
}
else
printf("\nstudent2 and student3 are different\n\n"); getch();
6.1.7. Operation on Individual Members
In a structure individual members are identified using the (.) dot operator. A member
with the dot operator along with its structure variable can be treated like any other
variable name and therefore can be manipulated using expression and operators.

Consider the program 4 one can perform the following operations:


if(studentl .number = =111) studentl .marks +=10.00;

float sum = studentl.marks+student2.marks;


student2.marks *= 0.5;

One can also apply increment and decrement operators to numeric type members.
Consider the following code segment to understand the increment and decrement
operators: student 1 ,number++;
++student 1 .number;

The precedence of the member operator is higher than all arithmetic and relational
operators and therefore no parentheses are required.

6.1.8. typedef and Its Use in Structure Declarations


A typedef declaration is a declaration with typedef as the storage class. The declarator
becomes a new type. Programmer can use typedef declarations to construct shorter or
more meaningful names for types already defined by C or for types that programmer
have declared.
Typedef names allow programmer to encapsulate implementation details that may
change.

A typedef declaration is interpreted in the same way as a variable or function


declaration, but the identifier, instead of assuming the type specified by the declaration,
becomes a synonym for the type.

The typedef feature allows users to define new data types that are equivalent to existing
data types.

Once a user-defined data type has been established, then new variables, arrays,
structures and so on, can be declared in terms of this new data type.

typedef type new-type;


Where type refers to an existing data type, either a standard data type, or a previous
user-defined data type, and new-type refers to the new user-defined data type. It should
be understood, however, that the new data type will be new in name only. In reality,
this new data type will not be fundamentally different from one of the standard data
types.

Program 5: To Prints the Weight of Various Sizes of Fruits.


#include<stdio.h>
typedef struct fruits {
float big; float
medium; float small;
} weight;

int main()
{
weight apples = {200.75,145.5,100.25}; weight
pears = {150.50,125,50}; weight mangoes =
{1000, 567.25, 360.25}; clrscrQ;
printf( \n\n apples: big %7.2fkg, medium %7.2fkg,
small %7-2fkg",apples.big,apples.medium,apples.small);
printf("\n\n pears: big %7.2fkg, medium %7.2fkg, small %7.2fkg", pears.big,
pears.medium, pears.small); ’
printf("\n\n mangoes:' big %7.2fkg, medium %7.2fkg, small %7.2fkg",
mangoes.big, mangoes.medium, mangoes);
return 0;
}
| DOSBai 8J4. Cpuspeed: man100X gete, Ranestap 0, Praga* TC

apples’-big 20Q.75kgi medium 145.50kg, small 100.25kg pears:

bir^SI.Sljj, medium 125.00kg, small 50,00kg mangoes: bigJ000.-81g,

medium 567.25kg, small 68742954123530330300,00kg,


***'\A . ■ ■
'. ». iV - J? x,

6.1.9. Nested Structures


C programmer can also take object of one structure as member in another structure.
Thus, structure within structure can be used to create complex data applications.
For example, the syntax of the structure within the structure is as follows:
struct school {
char[20] school_name; int
number_of_students;
};
struct students
{
int roll_number; char[20]
student_name; struct school
school_struct;
Now if one want to access the members of the school structure through student’s
structure then the follow this way: struct school sh;
sh.school_struct.school_name= “name of the school”;
sh.school_struct.number_of_students = 100; "
Program 6: To enter full name and date of birth of a person and display the same.
# include <stdio.h>
# include <conio.h> , void main ()
{
struct name {
char first[10];
char second[10];
char last[10];
};
struct b_date {
int day; int month; int year;
};
struct data {
struct name nm; struct b_date bt;
};
struct data rl; clrscr();
printf("\n Enter Name (First/Second/Last)\n"); scanf("%s %s %s" ,
rl.nm.first,rl.nm.second,rl.nm.last); printf("\n Enter Birth Date
Day/Month/Year\n"); scanf("%d c/d
%d",&rl.bt.day,&rl.bt.month,&rl.bt.year); printf("Name :%s %s
%s\n",rl.nm.first,rl.nm.second,rl.nm.last); printf("Birth Date
:%d.%d.%d",rl.bt.day,rl.bt.month,rl.bt.year); getch();
}
Output

6.1.10. Self-Referential Structure


A structure can have members which point to a structure variable of the same type.
These types of structures are called self-referential structures and are widely used in
dynamic data structures like trees, linked list, etc. The following is a definition of a self-
referential structure, struct node { int data;
struct node *next;
};
Here, next is a pointer to struct node variable.
It should be remembered that a pointer to a structure is similar to a pointer to any
other variable.
A C program contains the following structure declaration,
struct list_element {
char item[40];
struct list_element *nextj
};
This is a structure of type list_element. The structure contains two members - a 40-
element character array, called item, and a pointer to a structure of the same type (i.e.,
a pointer to a structure of type list_element), called next. Therefore this
is a self-referential structure.
Self-referential structures are very useful in applications that involve linked data
structures, such as lists and trees.
A self referential structure is one which contains a pointer to its own type. This is
illustrated by the following example. The structure Student has a pointer next, which
can point to another Student structure, struct Student {
int Rollno;
float Marks;
int subject;
struct Student
*next
};
In the above example, ptr is a pointer to a structure variable of the type Student.

Figure 6.2: Representation of Linked Lists

6.1.11. Array of Structures


Arrays of structures mean collection of structures, in other word array storing
different type of structure member variables.

Consider the following figure 6.3: , ,


p[0] " pin
---- 1 100 26 1 2J6 ------- Laptop 35 998.25 4.21
name I stock 1 price ’ 1 discount name stock price discount
Figure 6.3: Memory Arrangement of Array of Structure
In above figure, cell size does not represent actual byte taken by variables. Same color
cells represent structure whereas each cell represents each member variable of
structure.
Let s take an example to understanding the above figure concept. In this program there
is a product structure containing same member variables, struct product {
char name[30]; int
stock;
float price, discount;
};
Product p[2]; a product structure which consist of four member variables name,
stock, price and discount. So products p is an array of four, elements each. ’

Program 7: structure for storing Books information


1) #include<stdio.h>
2) #include<conio.h>
3)
3) struct product
4) {
5) char name[30];
6) int stock;
7) float price, discount;
8) };
10)
9) void main()
10) {
13)
11) struct product p[3j;
12) int i;
13) float temp;
14) clrscr();
18)
15) for(i=0;i<3;i++)
16) {
17) printf("Enter product name :");
18) gets(p[i].name);
23)
19) printf("\nEnter Stock :");
20) scanf("%d",&p[i], stock);
26)
2V) printf("\nEnter Price :");
28) scanf("%f',&temp);
29) p[i].price = temp;
30)
30) printf("\nEnter Discount:");
31) ^ scanf("%f',&temp);
32) p[i].discount = temp;
34)
33) printf("\n\n');
34) fflush(stdin);
35) }
38)
36) clrscr();
37) for(i=0;i<3;i++)
38) {
39) printf("Name=%s, Stock=%d, Price=$%.2f, Discount=%.2f%.\n", p[i].name.
p[i].stock, p[i].price,p[i].discount); ,
40) }
. 44) getch();
45) }
Output ______________ ,..
| D05ta'fL74, Cpu sped: i« TO cycles. Fnaeskip %Progaft: IC fliM
Hame-A, Stock=34, Price=$lZ8.88, Biscount=5.0ftt';. - :

HMB=B, Stock-78, Frice-$153.00, DiscouT)t=19,0&/. . ' ... name-C, Stock=60, Price^lffi.i,


liscount=3.0^.
Explanation: In the above program we store information about 3 different products.
Product information contains product name, stock, price and discount on pwrchf.se.
F-wp line no. 4 -9 declares product structure. Line no 14 declares an array of
structure which can store 3 products you increase or decrease its capacity by
replacing 3 by any positive integer. And Line no. 13 - 37 accepts data for products
from user and stores it to structure. Now we understand that he ' to store values in
array of structure, (figure below)

Name - A Stock - 34 Name - B Stock- Name - C Stock Price - 120.00


Discount - 5.00 78 Price - 159.00 - 60 Price -
Discount - 19.00 125.00 Discount
_____ p[0] _________________ _____________________________
- 3.00

In line no. 14 we declared product


structure variable p[3]. This means we have
three structures in an array p[0], p[l] and p[2]. Above figure represents the same.
So to store data in first index of structure variable (i.e. p[0]) we can write
following lines:
gets(p[0].name);
scanf(" %d", &p [0]. stock);
scanf("%f’,&p[0].price);
scanf("%f,&p[0].discount);
Above style for storing data is gooWor storing information of 1 or2 products but if
you have 100s of product then yoWhould use for loop because it is very convenient
and you don’t have to write lengthy code to do the same job.
Now we display stored data in p structure variable. Here also we used for loop
which loops for 3 times. So to display data in first index of structure variable (i.e.
p[0]) we can write following lines:
printf("%s", p[0].name);
printf("%d", p[0].stock);
printf("%.2f, p[0].price);
printf("%.2f', p[0].discount);

Program 8: Exercising the horses.


#include<stdio.h>
#include<ctype.h> int main(void)
{ 1 struct horse /* Structure declaration */
int age; int height; char name [20]; char father[20]; char mother[20];
}; /* Structure array declaration */
struct horse My_horses[50]; int /* Count of the number of horses */
hcount = 0‘ int i;
char test = '\0'; clrscr(); /* Test value for ending */
for(hcount = 0; hcount<50; hcount++)

scanf("%c", &test);
if(tolower(test) ==
'n') break;
printf("\nEnter the name of the horse:");
scanf("%s", My_horses[hcount].name); /* Read the horse’s name*/
printf("\nHow old is %s?", My_horses[hcount].name);
scanf("%d", &My_horses[hcount].age); /*Read the horse’s age */
printf("\nHow high is %s (in hands)?", My_horses[hcount].name);
/*Read the horse’s height*/
scanf("%d", &My_horses[hcount].height);
printf("\nWho is %s's father?", My_horses[hcount].name);
/* Get the father’s name */
scanf(" %s", My_horses[hcount].father);
printf("\nWho is %s's mother?", My_horses[hcount].name);
/* Get the mother’s name */
scanf("%s", My_horses[hcount] .mother);
}
Output

Program 9: To declare the array data type within a structure and to initialize
some of the structures and to display the contents of the structures.
#define MAX 5
#include<stdio.h>
main()
{
struct student}
char name[20];
long int rollno;
int age; .
char sex; •
float height; float weight;
};
static struct student class [MAX] = {
{"ravi", 91001, 25, 'M', 175.55, 56.7},
{"radha", 91002, 26, 'F, 167.22, 67.7},
{"kumari", 91003, 25, 'F, 180.2, 80.8},
{"sekar", 91004, 24, 'M\ 167.8,40.0}
};
int i;

printf("Contents of structure \n"); for(i=0; i<=MAX-l; i++)


{ x printf("Name: %s\n", class[i].name); printf("Roll no: %d\n", class[i].rollno);
printf("Age: %d\n", class[i].age); printf("Sex: %c\n", class[i].sex); ,
printf("Height: %0.2fVn", class[i].height);
printf( 'Weight: %0.2i\n', ciassfi],weight);
printffVi");
}
1

Note: In older version, the C compilers will not permit Programmer to copy or compare
the two structures as whole. One has to copy or compare as member by member but the
latest version allows one to copy or compare any forms.

6.1.12. Structures and Pointers


Pointer is a variable that holds the address of another data variable. The variable may
be of any data type, i.e., int, float, double, etc. In the same way pointer to structure is
defined. Over here starting address of member variables can be accessed. Thus, such
pointers are called structure pointers.
For Example
struct invent {
char name[25]; int
number; float
price;
• •/;
struct invent *ptr;
Here, *ptr is a pointer to structure invent. The syntax for using pointer with member
is as given below:
1) ptr —> name
2) ptr —► number
3) ptr —► price

Program 10: Illustrating Pointer to Structure Variables.


#include <stdio.h>
#include
<conio.h> struct
invent {
char *name[20];
int number; float
price;
};
main()
{ - struct invent product[3], *ptr; printf("INPUT\n\n");
for(ptr = product; ptr < product+3; ptr++)
scanf("%s %d %f", ptr->name, &ptr->number, &ptr->price); • printf
("\nOUTPUT\n\n"); ptr = product; while(ptr < product+3)
^ printf("%-20s %5d %10.2f\n",ptr->name,ptr->number,ptr->price);
ptr++;
}
getch();
}

While using structure pointers, we should take care of the precedence of operators.
The operators and V, and () and [] enjoy the highest priority among the operators.
They bind very tightly with their operands.
6.1.13. Structures and Functions
A function decomposes a complex program into a simpler one. It is therefore a very
powerful tool in C programming. It is possible to pass structure to a function as a single
variable instead of passing each member of the structure as an actual argument of the
function call which is unmanageable and insufficient when the structure size becomes
large.

A function can access the elements of a structure in the following ways:


1) Individual members can be passed as arguments to a function by both value by
and call by address.
2) The whole structure can be passed as an argument by value and function can
use the local copy of the structure.
3) The address of structure can be passed as an argument by reference.

Program 11: Illustrating structures and functions.


#include<stdio.h>
typedef struct coords }
{ /* create a point data type */
int x; inty;
} point;
void display (point
pt); int main()
{ /* function prototype */
point ptl,
pt2; ptl.x =
8; ptl.y = /* create structs of type point */
16; pt2.x = /* assign member values */
5; pt2.y =
10;
display(ptl)
; display /* pass structs to function */
(pt2);
return 0;

void display(point pt)


{
printf(“Point x: %d, y: %d\n”, pt.x, pt.y);
}
Output
6.1.14. Usage of Structure
1) Bundled information together connected by a common entity.
2) Structures could be used to hold the locations of points in multi-dimensional
space.
3) Structures can be used as members of other structures.
4) Structure uses as base data type for generation of complex data types like
linked lists, etc. .
5) Pointer referencing of structures makes them fit for usage as data passing tool
to functions.
6) Real-world entities of structures can be created.
7) Reusability of code. .
8) Structures are used as tools to reduce memory overheads by increasing
accessibility by other functions.
9) Structures provide function interdependence.
10) Tool to collect heterogeneous data type.

6.2. UNION
6.2.1. Definition
A derived data type, whose members share the same storage space, the members of
a union can be of any type and the number of bytes used to store a union must be at
least enough to hold the largest member.
Unions contain two or more data types. Only one member, and thus one data type,
can be referenced at a time. It is the programmer’s responsibility to ensure that the
data in a union is referenced with the proper data type and this is the weakness of
using union compared to struct.

6.2.2. Declaration of Union


A union is declared with the union keyword in the same format as a structure.

Syntax:
union union_name
{
<data_type> memberl <data_type> member2

. <data_type> membern
}
For example, following is a union declaration:
union sample {
int p; float q;
};
Indicates that sample is a union type with members’ int p and float q. The union
definition normally precedes the main() in a program so the definition can be used to
declare variables in all the program’s functions.
Only a value with same type of the first union member can be used to initialize
union in declaration part.
Memory space required for defining a variable of the union is max(sizeof(member
1), sizeof(member2)... sizeof(membem),).
Ways of Union Variable Declaration
Like structures, the C language also provides two ways to declare a union: , , ,
1) Tagged Union: The first way to declare a union is to use tagged union. A tagged
union can be used to define variables, arguments, and return types.
Syntax: The syntax for declaring a tagged union is:
union MIXTYPES {
Field list

For example,
union MIXTYPES { '
char
cVar; int
iVar;
float
fVar;
double
dVar;
};
The tagged union starts with the keyword union. The next element in the
declaration is tag. The tag is the identifier for the union, and will be used to
declare variable, arguments of the functions, and return types for the functions.
If we conclude the union declaration with semicolon after the closing brace, no
variables are defined. In this case, the union is simply a type template with no
associated storage.
2) Type-Defined Union: The more powerful way to declare a union is by using
type definition typedef.
Syntax: The syntax for declaring a type-defined union is:
typedef union { '
Field list

} TYPE;
For example,
typedef unien
{
char cVar; int
iVar; float
fVar; double
dVar;
} MIXTYPES; -

Difference between Tagged and Type-Defined Union


Type-defined union differs from tagged union in following aspects:
1) The keyword typedef is used before the union keyword.
2) Identifier after the union keyword is not mandatory as is the case with tagged
union.
3) Identifier is required after the closing brace and before the semicolon.
4) The variable can be declared with the declaration of tagged union whereas it
cannot be with type-defined unions.

Memory Representation of Union Variable


To understand how the elements of a union variable are stored in memory, consider
the following declarations:
typedef union {
char cVar; int
iVar; float fV
ar; double
dVar;
} EXAMPLE;
EXAMPLE e;

Memory Map

Figure 6.4: Memory Layout for Union Variable e


Syntax for declaring a type-defined union shows a conceptual view of the union
variable e and its relationship to memory, i.e., how its members are stored in
memory. Each variable has an address 2000.

However, the character value is stored in first byte, integer value in first two bytes,
float value in first four bytes, and double value in all the eight bytes.

6.2.3. Accessing and Initializing Members of Union


First declare the variable, the general declaration construct of a union:
union tag_name { ' member 1; member2;

memberN;
} variable 1, variable 2, variable 3,..., variableX;
Accessing Union Members
For accessing members of, say, variable 1 to N of the union tag_name, the
following constructs are used:
variablel.memberl
variable2.member2

variableX.memberN

Only a member that exists at the particular instance in storage should be accessed.

Initialisation of Union Member

The general construct for individual initialisation of a union member is:

variableX.memberN = constant;
Where, X is any value 1 to X and N is any value 1 to N.
Program 12: Illustrates the initialisation of a member in a union.
#include<stdio.h>
#include<conio.h>
union test /* declaration of union */
{ - int i; /* integer member */
char c; /* character member */
}var; /* variable */
int main() }
{ /* initialising integer member */
var.i = 65; /* output integer member */
printf("\n var.i = %d", var.i); /* output character member */
printf("\n var.c = %c", var.c);
return 0;
Output

Explanation
The figure 6.5 for the storage location of union test:
Bit _
position
15 14 13 12 11 10 9 8 7
0 0 0 0 0 0 0

char c

inti ■

Figure 6.5: Storage Location of Union Test, for a 16-Bit Machine

Figure 6.5 shows the storage location of union test. The location has two bytes because
the largest member in the union test is an integer named ‘i\ The other member, ‘c\ being
a character, occupies eight bits from bit 0 to bit 7. The integer member T is assigned the
value ‘65’. Hence, this value in binary form is stored in bits 0 to 15. So when printf() is
executed, the value 65 for T is printed on the screen. But the member ‘c’ has not been
assigned any value.
Therefore, the existing value of 65 in the referred storage location is taken when the
printf() for the member ‘char c’ is executed. Referring to the ASCII table, the
equivalent symbol for the decimal value 65 is ‘A’. Thus, when the second printf() is
executed, the output is ‘A’.

6.2.4. Operations on Union


The operations that can be performed on a union are:
1) Assigning a union to another union of the same type.
2) Taking the address (&) of a union.
3) Accessing union member using the structure member operator and the structure
pointer operator.
4) A union variable can be passed to a function.
Program 13: Illustrating Operation of a Union.
#include<stdio.h>
int main(void) •
{
union u_example {
float decval;
int pnum;
double
my_value;
}U1; .
Ul.my_value = 125.5;
Ul.pnum=10;
Ul.decval = 1000.5f;
printf(“\ndecval = %f pnum = %d my_value = %lf’,
Ul.decv.,1, U1 .pnum, Ul.my_value);
printf(“\nUl size = %d\ndecval size = %d pnum size = %d my_value”
“size = %d”, sizeof (Ul), sizeof (Ul),decval, sizeof (Ul.pnum), sizeof
(Ul.my_value)); return 0;
}

Explanation: This example demonstrates the structure and basic operation of a union.
Programmer declares the union Ul as follows: union u_example { ■ float decval; int
pnum; double my_value;
} Ul;
The three members of the union are of different types and they each require a different
amount of storage (assuming your compiler assigns 2 bytes to variables of type int).
With the assignment statements, you assign a value to each of the members of the
union instance Ul in turn:
Ul.my_value = 125.5;
Ul.pnum =10;
Ul.decval = 1000.5f;
Note: One can reference each member of the union in the same way as you do
members of a structure.

The next two statements output each of the three member values, the size of the union
Ul, and the size of each of its members. You get this output (or something close if your
machine assigns 4 bytes to variables of type int): decval = 1000.500000 pnum = 8192
my_value = 125.50016 U1 size = 8
decval size = 4 pnum size = 2 my_value size = 8
Last variable that was assigned a value is correct, and the other two have been
corrupted. This is to be expected, because they all share the same memory space. The
second thing to notice is how little the member my_value has been corrupted. This is
because only the least significant part of my_value is being modified.

In a practical situation, such a small error could easily be overlooked, but the ultimate
consequences could be terrible. You need to take great care when using unions that you
are not using invalid data.

Note: You can see from the output of the sizes of the union and its members that the
size of the union is the same as the size of the largest member.

6.2.5. Usage of Union


1) On most computers, the size of a pointer and an int are usually the same- this is
because both usually fit into a register in the CPU. So if you want to do a quick and
dirty cast of a pointer to an int or the other way, declare a union.
2) Union can be used in a command or message protocol where different size
messages are sent and received. Each message type will hold different information
but each will have a fixed part (probably a struct) and a variable part bit.
3) Unions are the same size, it makes sense to only send the meaningful data and not
wasted space.
4) A union, is a collection of variables of different types, just like a structure.
However, with unions, one can only store information in one field at any one time.
5) One can picture a union as like a chunk of memory that is used to store variables of
different types. Once a new value is assigned to a field, the existing data is wiped
over with the new data.
6) A union can also be viewed as a variable type that can contain many different
variables (like a structure), but only actually holds one of them at a time (not like a
structure). This can save memory if you have a group of data where only one of the
types is used at a time. The size of a union is equal to the size of it's largest data
member. In other words, the C compiler allocates just enough space for the largest
member. This is because only one member can be used at a time, so the size of the
largest, is the most you will need.

6.2.6. Difference between Union and Structure


The main difference between union and structure are shown in table below.
Table
Basis Structure Union
Definition A structure contains an A union is an object similar to a
ordered group of data structure except that all of its members
objects. start at the same location in memory.
Access One can access all the Only one member of union can be
Members members of structure at accessed at anytime. .
anytime.
Memory Memory is allocated for Allocates memory for variable which
Allocation all variables. variable require more memory.
Initialization All members of structure Only the first member of a union can be
can be initialized initialized.
Keyword ‘struct’ keyword is used ‘union’ keyword is used to declare
to declare structure. union.
Syntax struct struct name { union union name {
structure member 1; union member 1; union member 2;
structure member 2;
union member n; }union_var_nm;
structure member n;
}struct_var_nm;

Example struct item mst { union item mst {


int mo; char nm[50]; }it; int mo; char nm[50]; }it;

6.3. PROGRAMMING EXAMPLES


Program 14: To add two distance using structure.

#include <stdio.h>
#include <conio.h> struct Distance { int feet; float
inch;
} distance 1 ,distance2,sum;

main(){
printf("Enter information for First distance\n");
printf("Enter feet: ");
scanf("%d",&distancel.feet);
printf("Enter inch: ");
scanf(" %{'" ,&distance 1 .inch);
printf("\nEnter infromation for second distanceW);
printf("Enter feet: ");
scanf("%d",&distance2.feet);
printf("Enter inch: ");
scanf("%f',&distance2.inch);
sum.feet=distance 1 ,feet+distance2.feet;
sum.inch=distance 1 ,inch+distance2.inch;

/* If inch is greater than 12, changing it to feet. */ if


(sum.inch>12.0)
{
sum.inch=sum.inch-12.0;
++sum.feet;
printf("\nSum of distances=%d\'-%.lfV'",sum.feet,sum.inch);
getch();
}

w - _______ — ------------- ----- ----- * “■


Explanation: In this program, a structure(Distance) is defined with inch and feet as
its members. Then, three variables(distancel, distance2 and sum) of struct Distance
type is created. Two variables(distancel and distance2) are used for taking distance
from user and the sum of two distance is stored in variable sum and then, displayed.

Program 15: To add two complex numbers.


#include <stdio.h>
#include <conio.h>
typedef struct complex
{ float realnumber;
float imaginary;
}complex;

complex add(complex number 1,complex number2);

main(){
complex numberl,number2,temp;
printf("For 1st complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf(" %f%f' ,&number 1 .realnumber,&number 1 .imaginary);
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%f%f',&number2.realnumber,&number2.imaginary);
temp=add(number 1 ,number2);
printf("Sum=%. lf+%. lfi",temp.realnumber,temp.imaginary);
getchO;
}
complex add(complex number 1,complex number2){
complex temp;
temp.realnumber=numberl.realnumber+number2.realnumber;
temp.imaginary=numberl.imaginary+number2.imaginary;
retum(temp);
}
Output __
* G\Users\pravesh\Deslrtop\To\VTU.exe ' ‘ E3 I®

In this program structures number 1 and number2 are passed as an argument of


function add(). This function computes the sum and returns the structure variable
temp to the main() function.

Program 16: To calculate difference between two time period.


#include <stdio.h>
#include
<conio.h>
stract
TIME{ int
seconds;
int
minutes;
int hours;
};
void Difference(struct TIME tl, struct TIME t2, struct TIME *diff);
main(){ ’
struct TIME tl,t2,diff;
printf("Enter start time: \n");
printf("Enter hours, minutes and seconds respectively: ");
scanf("%d%d%d",&tl.hours,&tl.minutes,&tl.seconds);
printf("Enter stop time: \n");
printf("Enter hours, minutes and seconds respectively: ");
scanf("%d%d%d",&t2.hours,&t2.minutes,&t2.seconds);
Difference(tl,t2,&diff);
printf( \nTIME DIFFERENCE: %d:%d:%d- ",tl.hours,tl.minutes,tl.seconds);
printf("%d:%d:%d ",t2.hours,t2.minutes,t2.seconds); printf( =
%d:%d:%d\n",diff.hours,diff.minutes,diff. seconds);
getch();
}
void Difference(struct TIME tl, struct TIME t2, struct TIME *differ){
if(t2.seconds>t 1. seconds) {
—tl.minutes; tl.seconds+=60;
}
differ->seconds=t 1. seconds-t2. seconds; if(t2.minutes>tl .minutes) {
—tl.hours; tl .minutes+=60;
} . , differ->minutes=tl.minutes-t2.minutes;
differ->hours=tl ,hours-t2.hours;

Program 17: To store information of 5 students using structure.


#include <stdio.h>
#include <conio.h> struct student{ char name[50]; int roll; float marks;
};
main() {
struct student s[5]; int i;
printf("Enter information of students:\n"); for(i=0;i<5;++i)
{
s[i].roll=i+l;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf(" %f",&s [i] .marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<5;++i)
{
printf("\nInformation for roll number %d:\n",i+l);
printf("Name: ");
puts(s[i].name);
printf("Marks: %. lf",s[i].marks);
}
getch();
}
Output
- -- -------- - —....... .. .... _______________ .. . .
D\Users\prav^sh\Desktop\ToWTU.exc ; a ^ § S2 ________ j
. EXERCISE
1) What is a structure? Explain the advantages of using a structure.
2) What are the differences between structures and arrays? •-
3) Write a structure declaration statement to declare the following related items. Name the new data type
and declare two variables of that type. -
Employee Name ’
Employee ID
Weekly Hours
Worked Hourly
Wages Gross Pay
Deductions Net
Pay
4) What are possible solutions to the problem of having different memory spaces when pointers are
used? What are some of the trade-offs involved?

6) Explain STSTw between pointers to arrays and arrays of pointers. Make-up an example
Is toe any difference between an array and a pointer? What does it mean to say an array is the same
7)
as a pointer to the array?
8) What are some purposes for unions?
9) What do you mean by the following terms.
i) Nested structure
ii) Self referential structure
10) When do we use the following?
i) Bit fields
ii) The sizeof operator
11) What is wrong with the following code? Trace and correct the code.
struct •¥
{ : int month: char zodiacsign[15];
}sign = 10 , "Libra";

print data of 5 students.


13) What will be the output of the program?
#include<stdio.h>

int main()
{
union a {
int i;
char ch[2];
1;
union a u;
u.ch[0] = 3;
u.ch[l] = 2;
printf("%d, %d, %d\n", u.ch[0], u.ch[l], u.i);
return 0;
}
14) What will be the output of the program?
#include<stdio.h>

int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a); return 0;
15) What will be the output of the program?
#include<stdio.h>
int main()
{
struct value
{
int bitl: 1; '
int bit3:4; int bit4:4;
}bit={ 1, 2, 13};
printf("%d, %d, %d\n", bit.bitl, bit.bit3, bit.bit4);
return 0;

}
16) What will be the output of the program in 16 bit platform (Turbo C under DOS) 9
#mclude<stdio.h>

' int main()
{
struct value {
int bitl: 1;
int bit3:4;
int bit4:4;
}bit;
printf("%d\n", sizeof(bit)); return 0;
}
17) What will be the output of the program?
#include<stdio.h> int main()
{
enum days {MON=-l, TUE, WED=6, THU, FRI, SAT}-
printf("%d, %d, %d, %d, %d, %d\n", MON, TUE, WED,’ THU FRI SAT)- return 0;
’’’

You might also like