0% found this document useful (0 votes)
110 views59 pages

Chapter 10 Structures and Unions

This document discusses C structures. It defines a structure as a convenient way to group logically related data items of different types under a single name. Structures allow defining custom data types that pack together pieces of data. The document covers defining and declaring structures, initializing structure variables, accessing and comparing structure members, and operations on individual members. It also discusses word boundaries and slack bytes in structure storage.

Uploaded by

MD Saidur Rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views59 pages

Chapter 10 Structures and Unions

This document discusses C structures. It defines a structure as a convenient way to group logically related data items of different types under a single name. Structures allow defining custom data types that pack together pieces of data. The document covers defining and declaring structures, initializing structure variables, accessing and comparing structure members, and operations on individual members. It also discusses word boundaries and slack bytes in structure storage.

Uploaded by

MD Saidur Rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 59

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:

1. The keyword struct


2. the structure tag name
3. the name of the variable to be decalred
4. the assignment operator =
5. a set of values for the members of the st
ructure variable, separated by commas and
enclosed in braces
6. a terminating semicolon
Rules for Initializing Structures
There are a few rules to keep in mind while
initializing structure variables at compile-time:
1. We cannot initialize individual members inside
the structure template.
2. The order of values enclosed in braces must
match the order for 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:
•Zero for integer and floating point numbers.
•‘\0’ for characters and strings.
10.6 Copying and Comparing
Structure Variables
Two variables of the same structure type
can be copied the same way as ordinary
variables.
– person1 = person2;
– person2 = person1;
C does not permit any logical operation on
structure variables.
– person1 == person2
– person1 != person2
Do so by comparing members individually!
Example 10.2
Write a program to illustrate the
comparison of structure variables.

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];

Each element is defined An array called


to be of the type struct student, which consist
class. of 100 element.
Consider the following declarations:
struct marks{
int subject1;
int subject2;
int subject3;
};
main(){
struct marks students[3] =
{{45,68,81},{75,53,69},{57,36,71}};}

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);

printf("\n SUBJECT TOTAL\n\n");


printf("%s %d\n%s %d\n%s %d\n",
"Subject 1 ", total.sub1,
Output"Subject 2 ", total.sub2,
STUDENT TOTAL
"Subject 3 ", total.sub3);
Student[1] Total = %d\n",total.total);
printf("\nGrand 193
} Student[2] 197
Student[3] 164

SUBJECT TOTAL
Subject 1 177
Subject 2 156
Subject 3 221

Grand Total = 554


10.9 Array Within Structures
C permits the use of arrays as structure me
mbers.
Example
struct marks
{
int number;
float subject[3];
}student[2];
Access element using appropriate subsc
ripts:
student[1].subject[2];
Example 10.4
Rewrite the program of Example 10.3 using
an array member to represent the three
subjects.
main(){
struct marks{
int sub[3];
int total;
};
struct marks student[3]=
{45,67,81,0,57,36,71,0};
struct marks total;
int i, j;
for(i = 0;i <= 2;i++){
for(j = 0; j <=2;j++){
student[i].total+=student[i].sub[j];
total.sub[j]+=student[i].sub[j];
}
total.total += student[i].sub[j];
}
printf("STUDENT TOTAL\n\n");
for(i = 0;i<=2;i++)
printf("Student[%d] %d\n",i+1,student[i].total);
printf("\nSUBJECT TOTAL\n\n");
for(j = 0;j <= 2;j++)
printf("Subject-%d %d\n",j+1,total.sub[j]);
printf("\nGrand Total = %d\n",total.total);
}

Output
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164

SUBJECT TOTAL
Subject 177
Subject 156
Subject 221

Grand Total = 554


10.10 Structures Within Structures
Structures within a structure means nesting of
structures.
struct salary{
struct salary{
char name;
char name;
char department;
char department;
struct{
int basic_pay;
int dearness;
int dearness_allowance;
int house_rent;
int house_ret_allowance;
int city;
int city_allowance;
} allowance;
} employee;
} employee;

Access the inner-most member in a nested structure:


employee.allowance.dearness
employee.allowance
employee.allowance.house_rent
employee.house_rent
employee.allowance.city
An inner structure can have
more than one variable:
struct salary{

struct{
int dearness;

Both of them have the
} allowance,arrears; same structure template
} employee[100];

 A base member can be accessed as follows:


employee[1].allowance.dearness
employee[1].arrears.dearness
Use Tag Names to Define Inner
Structure:
struct pay {
int dearness;
int house_rent;
int city;
};
struct salary {
char name;
char department;
struct pay allowance;
struct pay arrears;
};
struct salary employee[100];
Nest more than one type of
structures:
struct personal_record
{
struct name_part name;
struct addr_part address;
struct data date_of_birth;
-------
-------
};
struct personal_record person1;
10.11 Structures and Functions
C support the passing of structure values as
arguments to functions.
Three methods by which the value of a
structure can be transferred from one
function to another:
– Pass each member of the structure as an actual
argument of the function call.
– Pass a copy of the entire structure to the called
function.
– Employ a concept called pointers to pass the
structure as an argument. In this case , the
address location of the structure is passed to the
called function.
The general format of sending a copy
of a structure to the called function is:
function_name (structure_variable_name);

The called function takes the following


form:
data_type function_name(struct_type st_name)
{
------
------
return (expression);
}
The following points are important to
note:
1. The called function must be declared for its type, appropriate
to the data type it is expected to return. For example, if it is
returning a copy of the entire structure, then it must be decl
ared as struct with an appropriate tag name.
2. The structure variable used as the actual argument and the co
rresponding format argument in the called function must be o
f the same struct type.
3. The return statement is necessary only when the function is r
eturning some data back to the calling function. The expressio
n may be any simple variable or structure variable of an expre
ssion using simple variables.
4. When a function returns a structure, it must be assigned to a
structure of identical type in the calling function.
5. The called functions must be declared in the calling function a
ppropriately.
Example 10.5
write a simple program to illustrate the
method of sending an entire structure as a
parameter to a function.
struct stores{
char name[10];
float price;
int quantity;
};
struct stores update(struct stores prodect,float
p,int q);
float mul(struct stores stock);
main(){
float p_increment, value;
int q_increment;
struct stores item={"XYZ", 25.75, 12};
printf("\nInput increment values:");
printf("price increment and quantity incremen
t \n");
scanf("%f %d", &p_increment, &q_increment);
/*--------------------------------------*/
item=update(item,p_increment,q_increment);
/*--------------------------------------*/
printf("Update values of item\n\n");
printf("Name :%s\n",item.name);
printf("Price :%f\n",item.price);
printf("Quantity :%d\n",item.quantity);
/*--------------------------------------*/
value = mul(item);
/*--------------------------------------*/
printf("\n Value of the item= %f\n", value);
Output
}
Input increment
struct stores values: stores
update(struct price product,
increment and
float p, i
quantity
nt q){ increment
10 12
product.price += p;
Updateproduct.quantity
values of item += q;
return(product);
Name
}
:XYZ
Price :35.750000
float mul(struct stores stock){
Quantity :24
return(stock.price * stock.quantity);
Value of the item = 858.000000
}
10.12 Unions
Unions are a concept borrowed from
structure and follow the same syntax as
structures.
There is major distinction between unions
and structures in terms of storage:
– Each member in structure has its own location.
– All the members of a union use the same
location.
Example
Storage of 4 bytes
union item{ 1000 1001 1002 1004
int m;
float x;
c
char c;
m
} code;
x

The compiler allocates a piece of storage that is large


enough to hold the largest variable type in the union.
we can use only one of them at a time. This is due to the
fact that only one location is allocated for a union variable,
irrespective of its size.
Access A Union Member
To access a union member
code.m In effect, a union creates
a storage location that can
code.x
be used by any one of its
code.c members at a time.
To access the member When
whose value is member
a different curre
ntly stored is assigned a new value, the
new value supersedes the
code.m = 379;
previous member’s value.
code.x = 7859.36;
printf(“%d”, code.m);
Union may be used in all places where a
structure is allowed.
The notation for accessing
The type aofunion member
the first
which is nested insidemember is int.
a structure remains
the same as for theOther nestedmembers can be
structures.
initialized by either
Unions may be initialized
assigningwhen the
values or variable
is declared. But unlike structures,
reading form the it can be
initialized only with keyboard.
a value of the same
type as the first union member.

union item abc = {100};

union item abc = {10.78};


10.13 Size of Structures
It is normal to use structures, unions and arrays cre
ate variables of large sizes. The actual size of thes
e variables in term of bytes may change from machi
ne to machine.
Using operation sizeof to tell us the size of a
structure.
Example
sizeof(struct x)
– Give the total number of bytes the structure x.
sizeof(y) y is the simple structure variable of type str
uct x
– Give the same answer.
sizeof(y) y is an array variable of type struct x
– Give the total number of bytes the array requires.
sizeof(y)/sizeof(x)
– Give the number of the elements in the array y.
10.14 Bit Fields
C permits us to use small bit fields to hold
data items and thereby to pack several
data items in a word of memory.
Bit fields allow direct manipulation of string
of a string of preselected bits as if it
represented an integral quantity.
A bit field is a set of adjacent bits whose
size can be from 1 to 16 bits in length. A
word can therefore be divided into a
number of bit fields.
The general form of bit field
definition :
struct tag-name{
data-type name1: bit-length;
data-type name2: bit-length;
------
data-type nameN: bit-length;
}
 The data-type is either int or unsigned int or signed
int and the bit-length is the number of bits used for t
he specified name.
 Remember that a signed bit field should have at leas
t 2 bits (one bit for sign).
 The bit-length is decided by the range of value to b
e stored. The largest value that can be stored is 2^n-
1, where n is bit-length.
Layout of Bit Fields
Assuming a 16-bit word that is ordered fro
m right to left.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

name N name 2 name 1


Several Specific Points to
Observe
1. The first field always starts with the first bit of the word.
2. A bit field cannot overlap integer boundaries. That is, the sum o
f lengths of all the fields in a structure should not be more than
the size of a word. In case, it is more, the overlapping field is au
tomatically forced to the beginning of the next word.
3. There can be unnamed fields declared with size. Example:
Unsigned : bit-length
Such fields provide padding within the word.
4. There can be unused bits in a word.
5. We cannot take the address of a bit field variable. This means w
e cannot use scanf to read values into bit fields. We can neither
use pointer to access the bit fields.
6. Bit fields cannot be arrayed.
7. Bit fields should be assigned values that are within the range of
their size. If we try to assign larger values, behavior would be u
npredicted.
Example
Suppose, we want to store and use personal information of emplo
yees in compressed form, this can be done as follows:
struct personal{
unsigned sex :1
unsigned age :7
unsigned m-status :1
unsigned children :4
} emp;

 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];

Declares emp as a 100 elements array of type struct


personal.
Example
struct pack{
The bit field a will be in
unsigned a : 2; one word, the variable
int count; count will be in the
unsigned b : 3; second word and the bit
} field b will be in the
third word. The fields a
and b would not get
packed into the same
word.
Homework
十个学生、四门课程,用结构体定义学生:
– 输入得到每个学生的 ID , Name ,每门课程的成绩
– 计算每个学生的平均成绩,排序后打印
– 计算每门课程的平均成绩,打印

You might also like