Sie sind auf Seite 1von 31

CHAPTER 6

Structures in C++
6.1 INTRODUCTION
A variable holds one piece of information or data at a given time. Arrays hold a number of pieces
of information or data of the same type. These two data types can solve a great variety of prob-
lems. But when you want to process many data items of different types together as a unit, then
these two types of definitions of data types are not sufficient. For example, when you want a
program dealing with data concerning employees in an organization, then you may want to store
the employees name (a character array), department number (an integer), salary (a floating point
number), etc. together as a unit. This is not possible using an array type of data structure, because
this array stores data of the same type. This is also not possible using multidimensional arrays.
Hence, we would need to use several different types of arrays a character array for names, a
floating point array for salary, etc. This approach although possible, is a tedious one. Moreover,
this approach hides the fact that you are dealing with a group of characteristics relating to a single
person, namely the employee. In order to solve such types of problems, C++ provides a special
data type, called structure.
6.2 STRUCTURE DEFINITION
The data type structure consists of a number of data items grouped together but unlike arrays,
each data item in the group need not be of the same type. Thus, for example, a structure may con-
tain employees data encompassing employees_name, employees_number, salary, and any other
relevant information about the employee. A structure can hold as many of these items as we need.
Figure 6.1 shows the differences between a simple variable, an array and a structure.
A structure date may be graphically represented as shown in Figure 6.2. A structure definition
is specified by the keyword struct followed by the user given name (also called tag). It is then fol-
lowed by the opening brace. Then it encloses the members of the structure followed by the closing
brace and the semicolon. The syntax of the structure is given below:
struct user_given_name
{
data_type member1;
data_type member2;
:
bpbonline all rights reserved
Part I Structures in C++ 127
:
data_type membern;
};
Figure 6.1
Simple vari-
able, array and
structure
41
Simple variable:
single data item
Array:
many data items
104
19
22
41
63
many data items
Structure:
S
41
2
4
,
5
6
6
.
5
0
K
R
A
E
H
of the same type
of different types
Figure 6.2
Graphical
representation
of structure
called date
Based on the above, the structure date may be defined as shown below:
struct date
{
int day;
int month;
int year;
};
date
day
month
year
struct
bpbonline all rights reserved
128 Programming in C++ Part I
6.2.1 A Simple Structure
Figure 6.3(a) shows a structure simple containing two data items an integer variable num and a
character variable ch. The program segment is shown in Figure 6.3(b).
The program demonstrates the three fundamental aspects of using structures, namely:
(a) Declaring the structure type
(b) Declaring structure variables
(c) Accessing elements of the structure
Figure 6.3(a)
Format of
structure
simple
De c la ring the Struc ture Typ e
The following statement declares the structure type with a tag simple. [Read the program shown in
Figure 6.3(b).]
Struct simple
{
int num;
char ch;
};
The above statement defines struct data type with the tag simple. It consists of two elements:
an integer variable called num, and a character variable called ch. This statement just tells the
compiler what the struct data type named simple looks like.
Program shown in Figure 6.3(b) uses struct simple for declaring variable ez1 and ez2 to be of
type simple.
Structures are useful, not only because they can hold different types of variables, but also
because they can form the basis for more complex structures.
struct simple
{
int num;
char ch;
};
Elements
surrounded
by braces
Semicolon terminates
entire statement
Keyword
This name is
called the " tag "
Elements
(or " members ")
of the structure
bpbonline all rights reserved
Part I Structures in C++ 129
/*program demonstrating use of structure*/
#include <iostream.h>
main()
{
struct simple /* definition of data type struct simple */
{int num;
char ch;
};
struct simple ez1; /* declares ez1 of data type simple */
ez1.num = 2; /* accessing elements of ez1 */
ez1.ch = z;
cout <<"ez1.num = " << ez1.num << endl;
cout << "ez1.ch = " << ez1.ch << endl;
}
Figure 6.3(b) Declaration of structure named simple containing two data items
The keyword struct introduces the structure. The name simple is called the "tag" or the "tem-
plate". It represents the format of the structure. The tag is a type name and not the variable name.
It can be used in the program as if it were a data type. The elements of the structure are surrounded
by braces ({ }), and the entire statement is terminated by a semicolon (;).
A structure format is defined by the programmer and can be used in a program as a data
type.
De c la ring Struc ture Ele me nts
After the declaration of structure data type, you may declare one or more variables to be of that
type. For example, in the program shown in Figure 6.3(b), you may declare variable ez1 to be of
type struct simple by writing the statement:
struct simple ez1;
This statement sets aside space in memory. It establishes enough space to hold all the items in
the structure. The variable declaration struct simple ez1; performs a function of declar-
ing ez1 to be a structure of the data type simple. This statement is very similar to the declaration of
a variable float salary or int count. The data type float informs the compiler what type
of the variable salary is going to be. And accordingly, it enables the compiler to set aside memory
for a variable of a specific type and gives a name to the variable. A very similar thing happens in
the case of structure variable declaration. Figure 6.4 illustrates what the structure variable ez1
looks like, first grouped together conceptually and then as the members of the structure stored in
the main memory of the computer.
bpbonline all rights reserved
130 Programming in C++ Part I
Figure 6.4
Structure ez1
stored in main
memory of the
computer
Use of Struc ture
The structure is used to store a "record" that may contain different data types. For example, an
employee record may contain the name (string variable), the department code (character variable),
etc. All such data items can be put together in one structure using the keyword struct. These can
then be accessed as a single unit using the tag given to the record as a whole. The following pro-
gram segment shows the declaration of the tag employee.
struct employee
{
char name[31];
char dept[4];
char SSN[12];
float pay_rate;
};
This template or tag defining employee can be used in a program as if it were another data
type. For example, you may declare a variable "employee_record" using the following declaration:
struct employee employee_record;
ez1
Structure variable
ez1
num
ch
Structure
stored in memory of structure
Symbolic representation
bpbonline all rights reserved
Part I Structures in C++ 131
Here employee_record is declared as the data type employee which indicates that struct
employee is functioning as if it is of a data type. Thus the general form of the structure definition
is:
struct structure_name
{
member_declaration;
member_declaration;
} variable list;
The variable "emplyee_record" is of the type struct employee. Right after the declaration a
portion of the main memory is reserved for the variable "employee_record". This variable takes a
size of 51 bytes for different structure members as follows:
(a) 31 bytes for "name"
(b) 4 bytes for "dept" code
(c) 12 bytes for "SSN"
(d) 4 bytes for the "pay_rate"
In the case of string variables, there is an extra byte allowed for NULL (/o) character. This
means 30 characters for name and one character for NULL (/o). Similarly, 3 characters for "dept"
code, and one for NULL. In the same way, 11 characters for the "SSN" and one for NULL. Here
SSN is the short form of Special Service Number. Each character takes one byte of memory space.
You can process the structure as a single unit for the following purposes.
(a) Initializing a structure
(b) Accessing the members of a structure
(c) Accessing the address of a structure
(d) Assigning one structure to another structure
Ac c e ssing Struc ture Ele me nts
A member of the structure can be accessed using the structure variable name and the member
name separated by the dot operator (.) as shown below:
employee_record.name;
employee_record.pay_rate;
You will notice that the dot operator (.) provides a powerful and clear way to specify members
of a structure. An expression like employee_record.pay_rate is easier to understand than
employee[29]. The variable employee[29] refers to 30th element of the array employee because
the first element of the array employee is employee[0].
To assign the numerical value 23.5 to the pay_rate, you may use the statement:
employee_record.pay_rate = 23.5;
bpbonline all rights reserved
132 Programming in C++ Part I
If you have more than one structure variable, (such as "employee_in" and "employee_out"),
you can move the data from one variable to the other. For example, you can assign one member to
the other like this:
employee_out.pay_rate = employee_in.pay_rate
You can also assign one structure variable to another:
employee_out = employee_in
By assigning this way, all the corresponding members of two structure variables become iden-
tical.
If the structure variables are declared and initialized inside a function, their storage class
must be static. The dot operator (.) connects a structure variable name with a member of
the structure.
For example, in Figure 6.5, ez1.num gets member num from the structure ez1. Similarly
ez2.num gets member num from structure ez2.
While accessing a structure member, note that before the dot, there must always be a
structure variable and after the dot there must always be a structure element.
6.2.2 Multiple Structure Variables of the Same Type
There can be more than one variable of a given structure type in a program. For example, in the
program shown in Figure 6.5, there are two variables, ez1 and ez2, both of the type struct simple.
/*program demonstrating the use of two structure variables*/
#include <iostream.h>
main()
{
struct simple /* definition of data type struct simple */
{
int num;
char ch;
};
struct simple ez1; /* declares ez1 to be of type simple */
struct simple ez2; /* declares ez2 to be of type simple */
ez1.num = 2; /* accessing elements of ez1 */
ez1.ch = z;
ez2.num = 3; /* accessing elements of ez2 */
(Contd...)
bpbonline all rights reserved
Part I Structures in C++ 133
ez2.ch = Y;
cout <<"ez1.num = " << ez1.num << endl;
cout << "ez1.ch = " << ez1.ch <<endl;
cout <<"ez2.num = " << ez2.num << endl;
cout << "ez2.ch = " << ez2.ch <<endl;
}
Figure 6.5 Declaration of multiple structure containing variables of the same type
You may also combine the declaration of structure type and structure variables in one state-
ment.
For example, the struct book defined in the following program segment can be used to combine
the declaration of b1, b2 and b3 as given below:
struct book
{
char name;
float price;
int pages;
};
struct book b1,b2,b3;
or the same can be done as given below:
struct book
{
char name;
float price;
int pages;
} b1,b2,b3;
This can also be done as shown below:
struct
{
char name;
float price;
int pages;
} b1,b2,b3;
Using the last method, we cannot declare any more structure variables other than those already
declared with the structure definition.
Structure variables can also be initialized where they are declared. The format is similar to that
used to initialize arrays. For example:
bpbonline all rights reserved
134 Programming in C++ Part I
struct book
{
char name[10];
float price;
int pages;
};
struct book b1 = {"Maths",130.00,500};
struct book b2 = {"Science",150.80,700};
In the above program segment, b1 and b2 are of the type book containing three members each.
The initial value for b1.name is Maths, b1.price is 130.00 and b1.pages is 500. Similarly, b2.name
is Science, b2.price is 150.80 and b2.pages is 700.
6.2.3 Entering Data into Structures
Figure 6.6 shows a program to construct a database for a typical employee category.
/*program demonstrating entering and accessing data for employees*/
#include <iostream.h>
main()
{
struct personnel /* definition of data structure */
{
char name[30]; /* employee name*/
int numb; /* employee number */
};
struct personnel emp1; /* declares structure variable emp1 */
struct personnel emp2; /* declares structure variable emp2 */
cout <<"Enter employee1 name" << endl;
cin >> emp1.name;
cout << "Enter employee1 number (3 digits)" << endl;
cin >> emp1.numb;
cout <<"Enter employee2 name" << endl;
cin >> emp2.name;
cout << "Enter employee2 number (3 digits)" << endl;
cin >> emp2.numb;
cout << "List of Employees" <<endl;
cout <<emp1.name <<" " <<emp1.numb<< endl;
cout <<emp2.name <<" " <<emp2.numb<< endl;
}
Figure 6.6 Entering and accessing data into structures
The structure variables emp1 and emp2 are declared to be of type struct personnel. Data is then
placed into the appropriate structure elements using the statements:
cin >>emp1.name;
bpbonline all rights reserved
Part I Structures in C++ 135
and
cin >>emp1.numb;
In the same way, the cout statements print out the contents of the database.
In the program shown in Figure 6.6, the database stores two items of information about each
employee. The name of the employee is represented by a string (character array) and the employee
number is represented by an integer. This information is entered into the program by the user. The
program reads and prints this information.
Figure 6.7 illustrates the method of storing each element of the structure emp1 in the main
memory of the computer. The element name[30] containing a string of maximum size 29 charac-
Figure 6.7
Structure emp1
stored in the
main memory
of the
computer
ters is stored in the consecutive locations in the main memory of the computer. (See right side of
Figure 1.7.) Similarly, the numb having 3 digits is stored consecutively in the main memory of the
computer.
Structure emp1
Structure
stored in memory of structure
Symbolic representation
H
a r
i
0 1 2 3 28 29
name[30]
102
H
a
r
i
102
numb
bpbonline all rights reserved
136 Programming in C++ Part I
Exa mp le 1
The program in Figure 6.8(a) shows a structure house_tag for the use of property dealers to store
data regarding various houses. The members of the structure are of different data types.
/* program demonstrating the definition and use structure */
#include <iostream.h>
#define NULL_STRING_TERMINATOR 1
#define MAX_VALID_CHARS 65
struct house_tag
{
char owner [ MAX_VALID_CHARS + NULL_STRING_TERMINATOR],
street[ MAX_VALID_CHARS + NULL_STRING_TERMINATOR],
city [ MAX_VALID_CHARS + NULL_STRING_TERMINATOR];
int bedrooms;
float price;
} A_House;
void main(void)
{
cout << "\n Who currently owns the house? ";
cin >> A_House.owner;
cout << "\n The house is on which street? ";
cin >> A_House.street;
cout << "\n The house is in which city? ";
cin >> A_House.city;
cout << "\n The house has how many bedrooms? ";
cin >> A_House.bedrooms;
cout << "\n What is the selling price? ";
cin >> A_House.price;
cout << "\n";
cout << "================ HOUSE 1 ================ ";
cout << "\n Owner: " << A_House.owner << endl;
cout << "\n Street: " << A_House.street << endl;
cout << "\n City: " << A_House.city << endl;
cout << "\n Bedrooms: " << A_House.bedrooms << endl;
cout << "\n Price: " << A_House.price << endl;
}
Figure 6.8(a) Structure for database of houses
The output of this program is shown in Figure 6.8(b). You should note here that A_House is of
the type struct house_tag. If this statement is contained within a function, then the structure,
named A-House, is local in scope to that function. If the statement is contained outside of all pro-
gram functions, the structure will be global in scope. In the program shown in Figure 6.8(a),
A_House has a global file scope since it was declared outside of all functions.
bpbonline all rights reserved
Part I Structures in C++ 137
Figure 6.8 (b)
Typical run of
the program
given in Fig-
ure 6.8 (a)
6.2.4 Assignment Statements used with Structures
It is possible to assign the value of one structure variable to another variable of the same type using
a simple assignment statement. That is if the structure of employee1 and employee2 are exactly
the same, you may use the statement employee2 = employee1;
The value of one structure variable can be assigned to another structure variable of the
same type.
6.2.5 Initialization of a Structure
A structure can be initialized by specifying the values of the data members just after the declara-
tion of the structure as shown in the program of Figure 6.9(a). The output is shown in Figure
6.9(b).
6.2.6 Local Scope for Data Members of a Structure
A field or member of a structure is a unique name for the particular structure. The same field or

Who currently owns the house? S.C.Jain

The house is on which street? C4F/271,

The house is in which city? Janakpuri,New-Delhi

The house has how many bedrooms? 3

What is the selling price? 120000

================ HOUSE 1 ================
Owner: S.C.Jain

Street: C4F/271,

City: Janakpuri,New-Delhi

Bedrooms: 3

Price: 120000

bpbonline all rights reserved
138 Programming in C++ Part I
/* program demonstrating structure initialization */
#include <iostream.h>
main()
{
struct personnel /* definition of data structure */
{
int numb; /* employee number */
int sal; /* employee salary */
};
personnel emp1 = { 123,4000 };/* initializing data for emp1*/
personnel emp2 = { 234,5000 };/* initializing data for emp2 */
cout << "List of Employees" <<endl;
cout << "employee1 number = " << emp1.numb << endl;
cout << "employee1 salary = " << emp1.sal << endl;
cout << "employee2 number = " << emp2.numb << endl;
cout << "employee2 salary = " << emp2.sal << endl;
}
Figure 6.9(a) Programfor initializing structure
Figure 6.9 (b)
Typical run of
the program
given in Fig-
ure 6.9 (a)
member name may be given to other structures with different data types. The C++ compiler will
treat each structure member as a separate variable and will reserve the memory space according to
the data type of the member. For example, the program shown in Figure 6.10 (a) defines struct first
and second with the same name of members, i.e. a, b, c but their types are different. Each member
of a structure has its scope confined to the structure in which it is defined. The compiler will be
able to differentiate the member a defined in structure first from the member a defined in
structure second. The output of the program is shown in Figure 6.10(b).
6.3 ARRAY-OF-STRUCTURES
The real power in using structures comes about when you use a collection of structures, called an
array-of-structures. By maintaining an array-of-structures, a database of information can be
manipulated for a wide range of items.
List of Employees
employee1 number = 123
employee1 salary = 4000
employee2 number = 234
employee2 salary = 5000
bpbonline all rights reserved
Part I Structures in C++ 139
/* program demonstrating two structure declaration */
#include<iostream.h>
struct first
{
int a;
float b;
char c;
} one;
struct second
{
int a;
float b;
char c;
} two;
void main (void)
{
one.a = 22;
one.b = 34.98;
one.c = f;
two.a = 14;
two.b = 56.98;
two.c = m;
cout << "\n Contents of the structure first \n";
cout <<one.a << \t << one.b << \t << one.c << endl;
cout << "\n Contents of the structure second \n";
cout << two.a << \t << two.b << \t<< two.c << endl;
}
Figure 6.10(a) Programfor demonstrating local scope of the member of a sturcture
Figure 6.10(b)
Typical run of
the program
given in Fig-
ure 6.10(a)
An array-of-structures is defined by the statement
struct personnel
{
char name[25];
int numb;
float height;

Contents of the structure first
22 34.98 f

Contents of the structure second
14 56.98 m

bpbonline all rights reserved
140 Programming in C++ Part I
};
struct personnel emp[MAXNUMB];
In order to declare an array-of-structures, we used the following statement after the declaration
of the structure personnel:
struct personnel emp[MAXNUMB];
An array-of-structures creates space in the main memory for storing data and accessing data of
a maximum of employees given in the variable MAXNUMB.
The above statement sets space equal to as many as MAXNUMB times of a single structure
and assigns this space to the structure of type personnel.
Figure 6.11 shows conceptually the array-of-structures as stored in the main memory of the
computer. The program using an array-of-structures is shown in Figure 6.12.
Figure 6.11
Array-of-struc-
tures concep-
tually shown
as stored in the
memory of a
computer
J a
U r
H a
emp[2].name
emp[2].numb
emp[2].height
emp[1].height
emp[1].numb
emp[1].name
emp[0].name
emp[0].numb
emp[0].height
bpbonline all rights reserved
Part I Structures in C++ 141
/* program to demonstrate keying into and accessing data from array of
structures*/
#include <iostream.h>
#include <stdio.h>
#define TRUE 1
#define MAXNUMB 2
void newempname (void);
void listallemp (void);
struct personnel
{
char name[25];
int numb;
float height;
};
struct personnel emp[MAXNUMB]; /* declaration of array-of-
structure */
void main(void)
{
char ch;
while (TRUE)
{
cout << "\n Type e to enter data for new employees" << endl;
cout << "\n Type l to list data of all employees " << endl;
ch = getchar();
switch (ch)
{
case e:
newempname(); /* for entry of new emplyee data */
break;
case l:
listallemp(); /* for display of the employees data */
break;
default :
cout << "\n Enter only e or l" << endl;
} /* end switch */
} /* end while */
} /* end main */
/* newempname() */
/* for entry of data of a new emplyee */
void newempname(void)
{
(Contd...)
bpbonline all rights reserved
142 Programming in C++ Part I
int n;
for (n = 0; n < MAXNUMB; n++)
{
cout << "\n Enter new employee name: " ;
cin >> emp[n].name;
cout << "\n Enter employee number ( 3 digits): ";
cin >> emp[n].numb;
cout << "\n Enter employee height (in cm): ";
cin >> emp[n].height;
}
}
/* for listing all employees data */
void listallemp(void)
{
cout << "\n LISTING OF DATA OF EMPLOYEES " << endl;
int j;
for (j = 0; j < MAXNUMB; j++)
{
cout<< "\n Record number" << j + 1 << endl;
cout <<"\n Employee Name: " << emp[j].name;
cout <<"\n Employee Number: " << emp[j].numb;
cout <<"\n Employee Height:" << emp[j].height;
}
}
Figure 6.12(a) Programdemonstrating use of array-of-structures
When the user of the program [Figure 6.12(a)] enters e, then the program allows the user to
enter data for the new employees. If the user types l, then the program lists the data of all
employees in the database. Figure 6.12(b) depicts the entry of data and Figure 6.12(c) shows the
display of data.
When working with an array-of-structures, be careful about the memory limitations of the
computer system you are programming on.
The only syntactic difference between referencing a structure member versus an array-
of-structures member is the use of the subscript. The array elements are accessed with the
help of a loop.
bpbonline all rights reserved
Part I Structures in C++ 143
Figure 6.12(b)
Typical run of
the program
given in Fig-
ure 6.12(a) for
entry of data

Type e to enter data for new employees

Type l to list data of all employees
e

Enter new employee name: Ram

Enter employee number ( 3 digits): 123

Enter employee height (in cm): 175

Enter new employee name: Mohan

Enter employee number ( 3 digits): 234

Enter employee height (in cm): 190^C
Figure 6.12(c)
Typical run of
the program
given in Fig-
ure 6.12(a) for
display of
entered data
6.3.1 Initialization of an Array-of-Structures
An array-of-structures can be initialized in the same way as an array of data in C++. The program
shown in Figure 6.13(a) initializes the data for the employee by initializing data immediately after
the declaration of the structure. The output of the program is shown in Figure 6.13(b).
/* program demonstrating array-of-structures initialization */
#include <iostream.h>
main()
{
struct personnel /* definition of data structure */
{
int numb; /* employee number */
int sal; /* employee salary */
};
(Contd...)
LISTING OF DATA OF EMPLOYEES

Record number1

Employee Name: Ram
Emloyee Number: 123
Employee Height:175
Record number2

Employee Name: Mohan
Emloyee Number: 234
Employee Height:190
bpbonline all rights reserved
144 Programming in C++ Part I
personnel emp[2] = {
{123,4000 }, /* initializing data for emp1*/
{234,5000 } /* initializing data for emp2 */
};
cout << "List of Employees" <<endl;
cout << "employee1 number = " << emp[0].numb << endl;
cout << "employee1 salary = " << emp[0].sal << endl;
cout << "employee2 number = " << emp[1].numb << endl;
cout << "employee2 salary = " << emp[1].sal << endl;
}
Figure 6.13(a) Programdemonstrating initialization of an array-of-structures
Figure 6.13(b)
Output of the
program given
in Fig-
ure 6.13(a)
6.3.2 Arrays within a Structure
C++ allows a structure to have a member of the array type. Its compiler allows to initialize the
members of a structure even if an array data type is a member of it. Program shown in Figure
6.14(a) demonstrates the use of array member name[20] which is of the type character. Note that
while initializing the structure, the character data is placed within the double quotes (" "). The
output of a typical run of that program is shown in Figure 6.14(b).
/* program demonstrating array within a structure */
#include <iostream.h>
#define MAX 2
void main(void)
{
struct personnel /* definition of data structure */
{
char name[20]; /* employee name */
int numb; /* employee number */
int sal; /* employee salary */
};
( Contd...)
List of Employees
employee1 number = 123
employee1 salary = 4000
employee2 number = 234
employee2 salary = 5000
bpbonline all rights reserved
Part I Structures in C++ 145
personnel emp[MAX] = {
{"Ramchander",123,4000 }, /* initializing data for emp1*/
{"Suraj",234,5000 } /* initializing data for emp2 */
};
cout << "List of Employees" <<endl;
cout << "emloyee1 name = " << emp[0].name << endl;
cout << "employee1 number = " << emp[0].numb << endl;
cout << "employee1 salary = " << emp[0].sal << endl;
cout << "employee2 name = " << emp[1].name << endl;
cout << "employee2 number = " << emp[1].numb << endl;
cout << "employee2 salary = " << emp[1].sal << endl;
}
Figure 6.14(a) Programdemonstrating initialization of structure containing an array
Figure 6.14(b)
Output of the
program given
in Fig-
ure 6.14(a)
The program shown in Figure 6.14(a) is rewritten using for loop for displaying the results. The
program is shown in Figure 6.15(a) and the output is shown in Figure 6.15(b).
/* program demonstrating array within a structure */
#include <iostream.h>
#define MAX 2
void main(void)
{
struct personnel /* definition of data structure */
{
char name[20]; /* employee name */
int numb; /* employee number */
int sal; /* employee salary */
};
(Contd...)
List of Employees
emloyee1 name = Ramchander
employee1 number = 123
employee1 salary = 4000
employee2 name = Suraj
employee2 number = 234
employee2 salary = 5000
bpbonline all rights reserved
146 Programming in C++ Part I
personnel emp[MAX] = {
{"Ramchander",123,4000 },/* initializing data for emp1*/
{"Suraj",234,5000 }/* initializing data for emp2 */
};
for (int i = 0; i <= MAX-1; ++i)
{
cout << "Data of Employee " << i + 1 <<endl;
cout << "employee name = " << emp[i].name << endl;
cout << "employee number = " << emp[i].numb << endl;
cout << "employee salary = " << emp[i].sal << endl;
cout << endl;
}
}
Figure 6.15(a) Programdemonstrating initialization of structure containing an array. Output is given
by using for loop structure
Figure 6.15(b)
Output of the
program given
in Fig-
ure 6.15(a)
While initializing an array-of-structures, if the data is not sufficient for all the members, then
the initial value of all such members is assumed to be zero. For example, in the program shown in
Figure 6.16(a), the value of MAX is three. It means there are three employees for whom the data
should be given. But the data given is only for two employees, therefore, the data for the third
employee is assumed to be zero as seen in Figure 6.16(b).
/* program demonstrating arrays within a structure */
#include <iostream.h>
#define MAX 3
void main(void)
{
struct personnel /* definition of data structure */
(Contd...)
Data of Employee 1
emloyee name = Ramchander
employee number = 123
employee salary = 4000

Data of Employee 2
emloyee name = Suraj
employee number = 234
employee salary = 5000

bpbonline all rights reserved
Part I Structures in C++ 147
{
char name[20]; /* employee name */
int numb; /* employee number */
int sal; /* employee salary */
};
personnel emp[MAX] = {
{"Ramchander",123,4000 }, /* initializing data for emp1*/
{"Suraj",234,5000 } /* initializing data for emp2 */
};
for (int i = 0; i <= MAX-1; ++i)
{
cout << "Data of Employee " << i + 1 <<endl;
cout << "employee name = " << emp[i].name << endl;
cout << "employee number = " << emp[i].numb << endl;
cout << "employee salary = " << emp[i].sal << endl;
cout << endl;
}
}
Figure 6.16(a) Programdemonstrating initialization of structures containing insufficient data
Figure 6.16(b)
Output of the
program given
in Fig-
ure 6.16(a)
6.4 PASSING STRUCTURE TO FUNCTIONS
As already explained, a function is a very useful aid to break a complex problem into separate
smaller parts or modules. Each such module may be assigned a function name and compiled sepa-
rately to test the proper running of each part. Finally, we invoke all the different functions in the
main program to get the complete solution of a complex problem.
Sometimes, a structure of data type can also be passed to a function as a single unit.

Data of Employee 1
emloyee name = Ramchander
employee number = 123
employee salary = 4000

Data of Employee 2
emloyee name = Suraj
employee number = 234
employee salary = 5000

Data of Employee 3
emloyee name =
employee number = 0
employee salary = 0

bpbonline all rights reserved
148 Programming in C++ Part I
The following program segment illustrates the method of passing a structure to a function.
#include <iostream.h>
struct simple
{
int x;
int y;
};
simple first; /* first declared as the structure of type simple */
void show (struct simple out); /* prototype function show */
void main(void)
{
show first /* calling function show in the main() block*/
}
void show (struct simple out) /* function show definition */
{
out.x = 15;
out.y = 25;
cout << "\n x = " << out.x << endl;
cout << "\n y =" << out.y << endl;
}
In the above program segment, the struct simple is used in the function show for getting the
desired output.
The program shown in Figure 6.17(a) declares the structure date containing day, month and
year as members. The function show uses the members of the structure date and displays the
member values.
\* program displaying contents of structure using function */
#include <iostream.h>
struct date
{
int day;
int month;
int year;
};
void show (struct date one); /* Function prototype */
void main (void)
{
(Contd...)
bpbonline all rights reserved
Part I Structures in C++ 149
date thisday;
thisday.day = 15;
thisday.month = 12;
thisday.year = 1996;
show(thisday);
}
void show (struct date one)
{
cout << "Todays date = " << one.day << endl;
cout << "Todays month = " << one.month << endl;
cout << "Todays year = " << one.year << endl;
}
Figure 6.17(a) Programshowing the contents of a structure date using function show
Figure 6.17(b)
Output of the
program given
in Fig-
ure 6.17(a)
The value of a structure variable can be passed as a parameter to a function. This helps in
writing well-constructed modular programs that use structures.
6.4.1 Pointers to Structures
To manipulate the data of a structure by a function, you do not need to pass a copy of the whole
structure to the function. You only need to pass the address of the structure to the function, then it
will have access to every member in the structure.
We can create a pointer to the address of a structure using the "*" operator. For example, if we
are using the structure "employee_record" given in the program shown in Figure 6.18(a), then the
pointer to the structure is:
*employee_record
In the program shown in Figure 6.18(a), the structure pointer is passed to two functions:
"read_info" and "display_info". The structure tag or template is declared globally at the beginning,
then the structure variable "emplyee_record" comes later in the main function as a local variable.
The argument of the function that handles the structure is a pointer of the type struct:
void read_info(struct employee *emp_rec)
We may omit the name of the pointer in the prototype as given below:
void read_info(struct employee *)
Todays date = 15
Todays month = 12
Todays year = 1996

bpbonline all rights reserved
150 Programming in C++ Part I
In this program you find a new operator "->" which is used with structures. It is called the
indirect membership operator and is used to refer to a member of a structure by using the pointer to
it. So if "emp_rec" is the pointer, then:
emp_rec->name refers to the "name" member and
emp_rec->SSN refers to the "SSN" member.
/*program demonstrating use of pointers to structures */
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define ASK(prompt,response) fputs(prompt,stdout); fgets(response,si-
zeof(response),stdin)
struct employee{
char name[30+2];
char dept[3 + 2];
char SSN[11 + 2];
float pay_rate;
}employee_record;
void read_info(struct employee *);
void display_info(struct employee *);
void hold_it(void);void read_info(struct employee *emp_rec)
{
char pay_string[5 + 2];
ASK("Employee name:",emp_rec->name);
ASK("Employee department (xxx):",emp_rec->dept);
ASK("SSN (###-##-####):",emp_rec->SSN);
ASK("Pay rate:",pay_string);
emp_rec->pay_rate=atof(pay_string);
}
void display_info(struct employee *empl_recrd)
{
cout<<"\n\nEmployee Information:\
\nName:"<<empl_recrd->name<<"\nDepartment:"<<
empl_recrd->dept<<"\nSSN:"<<empl_recrd->SSN<<
"\nPay rate:"<<empl_recrd->pay_rate<<"/hr."<<endl;
hold_it();
}
(Contd...)
bpbonline all rights reserved
Part I Structures in C++ 151
void hold_it(void)
{
char c;
cout<<"\nPress any key to continue..";
cin>>c;
}
main()
{
read_info(&employee_record);
display_info(&employee_record);
return(0);
}
Figure 6.18(a) Using pointers to structures
Figure 6.18(b)
Output of the
program given
in Figure 6.18(a)
The output of the program in Figure 6.18(a) is shown in Figure 6.18(b).
Note that the following two expressions mean the same thing:
emp_rec->name
(*emp_rec).name
In the second expression we must use the parentheses because the dot operator is of higher
precedence than the "*" operator.
6.5 USER DEFINED DATA TYPES
C++ provides two more ways of defining application specific data types using typedef and enum
declarations. Both these declarations help in clarifying program code.
Employee name:Mohan
Employee department (xxx):Sal
SSN (###-##-####):123-23-456
Pay rate:45


Employee Information:
Name:Mohan

Department:Sal

SSN:123-23-456

Pay rate:45/hr.

Press any key to continue..
bpbonline all rights reserved
152 Programming in C++ Part I
6.5.1 Use of Typedef for Declaring Structure Variables
Using the keyword typedef we can rename basic or derived data types, giving them names that
may suit our application or make our program simpler. Look at this declaration:
typedef unsigned long int ulong;
After this declaration the new type "ulong" becomes known to the compiler and is treated the same
as unsigned long int. Now if we want to declare more variables of this type, we can use the newly
defined type as in:
ulong distance;
We may also use typedef with structures, as in the following example:
typedef struct
{
char name[30 +1];
char dept[3 + 1];
float pay_rate;
} record;
This definition creates a new variable "record." We can now declare a structure variable as fol-
lows:
record employee_record;
Thus employee_record is a structure variable of the type record defined earlier.
We do not have to use the keyword struct again because the new type "record" refers to the
same structure.
6.5.2 Enumerated Data Types
De finitions
Enumerated data types let us define sets. These are used to express special data items that can fit
into an ordered series, like the days of the week or the months of the year.
De c la ra tion
To declare an enumeration for the days of the week, the keyword enum is used as in the statement:
enum weekdays{mon,tue,wed,thu,fri,sat,sun};
According to this declaration, every day in the enumeration will possess an int value starting
from zero. Therefore, "mon" will contain the value "0", "tue" will contain the value "1" and so on.
The program shown in Figure in 6.19 uses the enum type of data.
The output of the program will be:
1 2 3 4 5 6 7 8 9 10 11 12
bpbonline all rights reserved
Part I Structures in C++ 153
/*program demonstrating the use of enum declaration */
#include <iostream.h>
main()
{
enum month_name {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
int month;
for (month=jan; month<=dec; month++)
cout << month+1 << " " ;
return(0);
}
Figure 6.19 Programusing enumerated data type
Note that the value of jan is printed as 1 and not zero. It is because in the cout statement in
Figure 6.19, we have used the (month + 1) and not month. The first value of month is zero and
adding 1 to it gives the value as 1.
Another useful application of the enumerated data type is:
enum Bool{FALSE,TRUE}; //FALSE=0,TRUE=1
The value of the variable FALSE is zero and that of TRUE is one.
6.5.3 Changing Default Ordinal Values
If we want to change the default value, then we need to specifically declare a different value as
given in the following example:
enum {red, white = 12, blue} flag_colors;
The first term "red" gets a value "0". But the value of white is specifically declared as 12 and the
value of blue will be (12+1) or 13. We cannot use the names of the enum members as names of
other variables. For example:
int red;
when red is declared as the enumerated type it will be flagged as error by the compiler.
6.5.4 Symbolic Constants
The program in Figure 6.20(a) uses the #define statement INVALID_DEGREE - 1.
This statement allows a programmer to define a string, INVALID_DEGREE, whose value is
-1 and this value is searched for in the file, before the program is compiled. Every string occur-
rence is replaced with the second string, namely (-1).
Symbolic constants make a program more readable and prevent possible side effects by
creating a constant (locked value) rather than a variable (changeable value).
bpbonline all rights reserved
154 Programming in C++ Part I
/* Program demonstrates symbolic constant.*/
/* It converts temperature in Celsius to Fahrenheit */
#include <iostream.h>
#define INVALID_DEGREE -1 /* Symbolic Constant */
int main( void )
{
int DegreeInCelsius; /* Variable Declarations */
float DegreeInFahrenheit;
cout << "Enter a degree in Celsius: ";
cin >> DegreeInCelsius;
while( DegreeInCelsius != INVALID_DEGREE )
{
DegreeInFahrenheit = DegreeInCelsius * 1.8 + 32.0;
cout << "\n DegreeInCelsius = " << DegreeInCelsius;
cout << "\n DegreeInFahrenheit = " << DegreeInFahrenheit;
cout << "\n Enter a degree in Celsius (-1 terminates): ";
cin >> DegreeInCelsius;
}
cout << "\n ==> Successful Termination <== ";
return(0);
}
Figure 6.20(a) Programusing symbolic constant
Figure 6.20(b)
Output of the
program given
in Fig-
ure 6.20(a)
Enter a degree in Celcius: 132

DegreeInCelcius = 132
DegreeInFahrenheit = 269.600006
Enter a degree in Celcius (-1 terminates): 100

DegreeInCelcius = 100
DegreeInFahrenheit = 212
Enter a degree in Celcius (-1 terminates): -1

==> Successful Termination <==

bpbonline all rights reserved
Part I Structures in C++ 155
TEST PAPER
Time: 3 Hrs
Max Marks: 100
Answer the following questions.
1. Fill in the blanks:
Array elements must all be of the _______________, whereas structure members can be
of ______________________.
2. The purpose of declaring a structure type is to:
(a) Set aside the appropriate amount of memory.
(b) Define the format of the structure.
(c) Specify a list of structure elements.
(d) Define a new data type.
3. Write a statement that declares a structure type consisting of two elements: a string of 10
characters and an integer.
4. How many structure variables of a given type can you use in a program?
(a) one
(b) none
(c) as many as you like
(d) as many as there are members in the
structure
5. Write a statement that will declare a structure variable car to be of the type vehicle.
6. Assume the following declaration for the structure body:
struct body
{
int arm;
int legs;
}struct body mohan;
Write an assignment statement that will set the number of arms in mohans body equal
to 2.
7. Assuming that struct1 and struct2 are structure variables of the same type and contain
the same number of members, is the following statement possible?
struct1 = struct2;
8. Write a program in C++ that will:
(a) set up a structure to hold a date. The structure will consist of three integer values,
for the month, day, and year.
(b) Assign values to the members of the structure
(c) Print out the values in the format 12/31/97
bpbonline all rights reserved
156 Programming in C++ Part I
9. Modify the program in Q 8 so that the date is printed out by a function. Pass the structure
to the function.
10. Write a program in C++ to create a database with the following items using structured
data type with the tag patient_history.
(a) patient_name
(b) patient_admission_number
(c) sex
(d) date_of_admission
Your program should be able to do the following:
(i) Insert a new entry.
(ii) Delete an entry.
(iii) Edit an entry.
11. Write a program in C++ to create a library information system which includes the fol-
lowing data members:
(a) access_number
(b) author_name
(c) book_title
(d) price
The program should be able to do the following:
(i) Insert a new entry.
(ii) Delete an entry.
(iii) Edit an entry.
12. Distinguish the structure data type from other data type variables.
13. What is the difference between declaration of a structure and initialization of a structure?
Summarize the rules governing the declaration of a structure.
14. How is a structure different from an array in C++? Give an example of each.
15. What is meant by an array of fields in a structure and how is it different from an array?
bpbonline all rights reserved

Das könnte Ihnen auch gefallen