Chapter 10 Structures and Unions
Chapter 10 Structures and Unions
1
10.1 Introduction
An array can’t represent a collection of
data items of different types using a single
name.
C supports a constructed data type known
as structures, a mechanism for packing data
of different types.
A structure is a convenient tool for handling
a group of logically related data items.
The concept of a structure is analogous to
that of a ‘record’ in many other language.
Examples of Structures
time : seconds, minutes, hours
date : day, month, year
book : author, title, price, year
city : name, country, population
address : name, door-number, street
inventory : item, stock, value
10.2 Defining a Structure
Structures must be defined first for their f
ormat that may be used later to declare str
ucture variables.
Example
title
struct array of 20 Name
book_bank
of the structure,
characters
author called the structure tag.
{ array of 15 characters
Declareschar title[20];
pages integer
a structure
char author[15]; Structure elements
price float
int pages; or members.
float price;
};
The General Format of a
Structure Definition:
struct tag_name
{
data_type member1;
data_type member2;
… …
… …
};
Defining a structure you may
note the following syntax:
1. The template is terminated with a semicolo
n.
2. While the entire definition is considered a
s a statement, each member is declared ind
ependently for its name and type in a separ
ate inside the template.
3. The tag name such as book_bank can be us
ed to declare structure variables of its typ
e, later in the program.
Arrays Vs Structures
Both the array and structures are classified as
structured data types as they provide a
mechanism that enable us to access and
manipulate data in a relatively easy manner.
1. An array is a collection of related data
elements of same type. Structure can have
elements of different types.
2. An array is derived data type whereas a
structure is a programmer-defined one.
3. Any array behaves like a built-n data type. All
we have to do is to declare an array variable and
use it. But in the case of a structure, first we
have to design and declare a data structure
before the variables of that type are declared
and used.
10.3 Declaring Structure
Variables
A structure variable declaration is similar t
o the declaration of variables of any other
data types. It includes the following elemen
ts:
1.The keyword struct.
2.The structure tag name.
3.List of variable names separated by commas
4.A terminating semicolon.
Example
struct book_bank book1, book2, book3;
Structure
Not recommended:
Declaration
1. Without a tag name, we
Combine
cannot both
use it for the structure definition and
future
declarations.
variables declaration in one statement:
2. Normally, structure
definition appear at the
struct book_bank struct
beginning of the program
{
file, before any variables or {
functions char title[20];
are defined. They ------
char author[15];
may also appear before the ------
main, alongint
with macro
pages; ------
definitions, such as #define.
float price; } book1, book2, boo
In such cases, the definition
} book1,
is global and can book2, boo
be used by k3;
otherk3;functions as well.
Type-Defined Structures
We can also use the keyword typedef to define
a structure as follows:
typedef struct{
…
type member1;
type member2;
…
} type_name;
The type_name represents structure definition
associated with it and therefore can be used to
declare structure variables as shown below:
type_name variable1, variable2,…;
Remember that:(1). The name type_name is the
type definition name, not a variable. (2). We ca
nnot define a variable with typedef declaration.
10.4 Accessing Structure
Members
Access and assign values to the members of
a structure by using the member operator ‘.’:
book1.price
Assign values to the members of book1:
strcpy(book1.title, “BASIC”);
strcpy(book1.author, “Balagurusamy”);
book1.pages = 250;
book1.price = 120.50;
Use scanf to give the values through the key
board:
scanf(“%s\n”,book1.title);
scanf(“%d\n”,&book1.pages);
Example 10.1
Define a structure type, struct person that
would contain person name, date of joining
and salary. Using this structure, write a pr
ogram to read this information for one pers
on from the keyboard and print the same o
n the screen.
struct personal
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
main()
{
struct personal person;
printf(“Input Values\n”);
scanf(“%s %d %s %d %f”,
person.name,
&person.day,
person.month,
&person.year,
&person.salary);
Output
printf (“%s %d %s %d %f\n”,
person.name, Input Values
person.day, M.L.Goel 10 January 1945 4500
person.month,M.L.Goel 10 January 1945 4500.00
person.year,
person.salary);
}
10.5 Structure Initialization
A structure variable can be initialized at
compile time:
main()
{
struct
{ Assign 180.75 to
int weight; student.height
float height;
}
student = {60, 180.75};
------ Assign 60 to stu
------
dent.weight
}
Initialize two structure variables:
main()
{
struct st_record
{
int weight;
float height;
};
struct st_record student1 = {60, 180.75};
struct st_record student2 = {53, 170.60}
------
------
}
Initialize a structure variable outside the function:
struct st_record
{
int weigth;
float heigth;
} student1={60,180.75};
main()
{
struct st_record student2 = {53, 170.60};
------
------ Here, it is essential to
use a tag name.
}
The compile-time initialization a structure
variable must have the following elements:
struct class{
int number;
char name[20];
float mark;
};
main(){
int x;
struct class student1={1,”Rao”,72.1};
struct class student2={2,”Red”,67.0};
struct class student3;
student3 = student2;
x = ((student3.number == student2.number) &&
(student3.mark == student2.mark)) ? 1:0;
if(x == 1){
printf(“\nstudent2 and student3 are
same.\n\n”);
printf(“%d %s %f\n”,student3.number,
student3.name,student3.mark);
}
else
printf(“\nstudent2 and student3
Output are different.\n\n”);
student2 and student3 are same.
}
2, Red, 67.000000
Word Boundaries and Slack Bytes
Computer stores structures using the concept of “word b
oundary”. The size of a word boundary is machine depend
ent.
In a computer with two bytes word boundary, the membe
rs of a structure are stored left_aligned on the word bou
ndary as shown next page.
Slack byte
0 1 2 3
|- char -| |-> int <-|
When we declare structure variables, each one of them m
ay contain slack bytes and values stored in such slack byt
es are undefined.
So even if the members of two variables are equal, their
structures do not necessarily compare equal.
10.7 Operations on Individual
Members
The individual members are identified using
the member operator, the dot.
A member with the dot operator along with
its structure variable
– treated like any other variable name
– manipulated using expressions and operators
Example
if(student1.number == 111){
student1.number ++;
++student1.marks += 10.00;
student1.number;
}
float sum = student1.marks+student2.marks;
student2.marks *= 0.5;
Three Ways to Access Members
We have used the dot operator to access the
members of structure variables. In fact, the
re are tow other ways. Consider the following
structure:
typedef struct{
int x; ptr is known as pointer
int y; that has been assigned t
} he address of the struct
VECTOR v, *ptr; ure variable v
ptr = &v;
Now, the members can be accessed in three
ways: These will be considered in chapter 11
Using dot notation : v.x
Using indirection notation : (*ptr).x
Using selection notation : ptr->x
10.8 Arrays of Structures
We may declare an array of structures, ea
ch element of the array representing a stru
cture variable.
Example
struct class student[100];
Initialize
student[0].subject1 = 45;
student[0].subject2 = 68;
…
…
student[2].subject3 = 71;
The Array Student Inside memory
student[0].subject1 45
subject2 68
subject3 81
student[1].subject1 75
subject2 53
subject3 69
student[2].subject1 57
subject2 36
subject3 71
Example 10.3
For the student array discussed above,
write a program to calculate the subject-
wise totals and store them as a part of the
structure.
struct marks{
int sub1;
int sub2;
int sub3;
int total;
};
main(){
int i;
struct marks student[3]=
{{45,67,81,0},{75,53,69,0},{57,36,71,0}};
struct marks total;
for(i = 0; i <= 2;i++){
student[i].total = student[i].sub1 +
student[i].sub2 + student[i].sub3;
total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub1+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+1, student[i].total);
SUBJECT TOTAL
Subject 1 177
Subject 2 156
Subject 3 221
Output
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164
SUBJECT TOTAL
Subject 177
Subject 156
Subject 221
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
This defines a variable name emp with four bit fields. The r
ange of values each field could have is follows:
Bit field Bit length Range of value
sex 1 0 or 1
age 7 0 or 127(2^7-1)
m_status 1 0 or 1
children 3 0 or 7(2^3-1)
Example
Assignment statement:
– emp.sex = 1;
– emp.age = 50;
Remember, we cannot use scanf to read val
ues into a bit field. We may have to read i
nto a temporary variable and then assign it
s value to the bit field.
– scanf(“%d %d”, &AGE, &CHILDREN);
– emp.age = AGE;
– emp.children = CHILDREN;
One restriction in accessing bit fields is tha
t a pointer cannot be used. However, they
can be used in normal expressions like any o
ther variable.
Example:
sum = sum + emp.age;
if(emp.m_status) ……;
printf(“%d\n”, emp.age);
Combine normal structure
elements with bit field elements
struct personal{
char name[20];/*normal variable*/
struct addr address;
/*structure variable*/
unsigned sex : 1;
} emp[100];