C++ ch3
C++ ch3
CHAPTER THREE
3. STRUCTURES
3.1. Introduction
In many occasions what we want to store are not mere sequences of elements of the same data
type (as in arrays), but sets of different elements with different data types. Structures offer a way
of joining these heterogeneous elements together to form complex structures.
A structure is a group of data elements grouped together under one name. These data elements
known as members (also called fields) can have different types, some can be int, some can be
float, some can be char and so on, and different lengths.
The difference between array and structure is the element of an array has the same type while the
elements of structure can be of different type. A structure is heterogeneous (composed of data of
different types). In contrast, array is homogeneous since it can contain only data of the same
type. Another difference is that each element of an array is referred to by its position while each
element of structure has a unique name.
Student record: student id, name, major, gender, start year etc.
Where struct is a keyword, structure_name is a valid identifier name for the structure type;
object_name can be a set of valid identifiers for objects that have the type of this structure.
Within braces { } there is a list with the data members (structure variables), each one is specified
with a data type and a valid identifier as its name.
For example:
Three variables: custnum of type int, salary of type int, commission of type float are structure members
and the structure name is Customer. This structure is declared as follows:
In the above example, it is seen that variables of different types such as int and float are grouped
in a single structure name Customer. Arrays behave in the same way, declaring structures does
not mean that memory is allocated. Structure declaration gives a skeleton or template for the
structure.
The first thing we have to know is that a structure creates a new type: Once a data structure is
declared, a new type with the identifier specified as structure_name is created and can be used in
the rest of the program as if it was any other type. After declaring the structure, the next step is to
define a structure variable.
#include<iostream.h> #include<iostream.h>
struct customer struct customer
{ {
int custnum; int custnum;
char name[10]; char name[10];
int phonenum; int phonenum;
}cust1,cust2,cust3;//structure variable declarn };
int main( ) int main( )
{ {
…. struct customer cust1,cust2,cust3;//structure variable declaration
} }
What happens when this is defined? When structure is defined, it allocates or reserves space in
memory. The memory space allocated will be cumulative of all defined structure members. In
the above example, there are 3 structure members: custnum, name and phonenum. If integer
space allocated by a system is 2 bytes and char one bytes the above would allocate 2 bytes for
custnum, 2 bytes for phonenum and 10 bytes for name; hence a total of 14 bytes for the structure.
operator, you can treat each structure member almost as if it were a regular non-structure
variable.
A structure variable name must always precede the dot operator, and a member name must
always appear after the dot operator. Using the dot operator is easy, as the following examples
show.
#include<iostream.h> #include<iostream.h>
struct customer struct customer
{ {
int custnum; int custnum;
char name[10]; char name[10];
int phonenum; int phonenum;
}cust1; };
int main ( ) int main ( )
{ {
cout<<”Enter customer number”<<endl; struct customer cust1;
cin>>cust1.custnum; cout<<”Enter customer number”<<endl;
cout<<”Enter customer name”<<endl; cin>>cust1.custnum;
cin>>cust1.name; cout<<”Enter customer name”<<endl;
cout<<”Enter customer phone number”<<endl; cin>>cust1.name;
cin>>cust1.phonenum; cout<<”Enter customer phone number”<<endl;
cout<<”Customer cin>>cust1.phonenum;
Number:”<<cust1.custnum; cout<<”Customer
cout<<”\nCustomer Name:”<<cust1.name; Number:”<<cust1.custnum;
cout<<”\ cout<<”\nCustomer Name:”<<cust1.name;
nCustomerPhone:”<<cust1.phonenum; cout<<”\
} nCustomerPhone:”<<cust1.phonenum;
}
For example:
A programmer wants to assign 2000 for the structure member salary in the structure Customer
with structure variable cust1. This is written as:
For example
Initializing members at declaration Initializing members at the body of the program
#include<iostream.h> #include<iostream.h>
struct employee #include<string.h>
{ struct employee
char Emp_id[10]; {
char Name[20]; char Emp_id[10];
float Salary; char Name[20];
}emp1={“DMU/001”,”Zerihun”,2808}; float Salary;
int main() }emp1;
{ int main()
cout<<”Your id:”<<emp1.Emp_id<<endl; {
cout<<”Your name:”<<emp1.Name<<endl; strcpy(emp1.Emp_id,”DMU/001/”);
cout<<”Your salay”<<emp1.Salary<<endl; strcpy(emp1.Name,”Zerihun”);
} emp1.Salary=2808;
cout<<”Your id:”<<emp1.Emp_id<<endl;
cout<<”Your name:”<<emp1.Name<<endl;
cout<<”Your salay:”<<emp1.Salary<<endl;
}
NB. Be sure that your computer does not run out of memory when you create a large number of
structures. Arrays of structures quickly consume valuable information.
You can also define the array of structures after the declaration of the structure.
struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream.h>
int main()
{
struct Company store[1000]; //the variable store is array of the structure Company
…
}
For example:
struct Book
{
char title[50];
int year;
};
struct student
{
char name[50];
char email[50];
Book favourite_Book;
} S1, S2;
Therefore, after the previous declaration we could use the following expressions (for example):
S1.name
S2.favourite_Book.title
S1.favourite_Book.year
For example, in the following program, we have the structure address nested in structure
employee to access member of a nested structure, we use the dot operator twice.
#include<iostream.h>
struct address
{
char street [30];
int distance;
};
struct employee
{
address branch;
char name[20];
};
int main ( )
{
employee emp1;
cout<<”Enter employee name: ”;
cin>>emp1.name;
cout<<”Enter branch street of the employee: “;
cin>>emp1.branch.street;
7|Page Fundamentals of Programming-II(ITec 2042)
Debremarkos University Department of software Engineering
Ok, we will now go with another example that will serve to introduce a new operator
// pointers to structures
#include <iostream.h>
struct Book
{
char title[50];
int year;
};
int main ( )
{
char buffer[50];
Book b1;
Book * pb1;
pb1 = &b1;
cout<< "Enter title of the book: ";
cin.getline (pb1->title, 50);
cout<< "Enter publication year: ";
cin.getline (buffer, 50);
pb1->year = atoi (buffer);
cout<< "\n The book information is:\n";
cout<<”Title: “<< pb1->title;
cout<< ", and it is published in " << pb1->year << "\n";
}
The previous code includes an important introduction: operator->. This is a reference operator
that is used exclusively with pointers to structures and pointers to classes. It allows us not to have
to use parenthesis on each reference to a structure member. In the example we used:
pb1->title
could also be translated to:
(*pb1).title
Both expressions pb1->title and (*pb1).title are valid and mean that we are evaluating the
element title of the structure pointed by pb1.
#include <iostream.h>
void printBook( struct Books book );
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan"); OUTPUT
strcpy( Book1.subject, "C++ Programming"); Book title : Learn C++
Book1.book_id = 6495407; Programming
// book 2 specification Book author : Chand Miyan
strcpy( Book2.title, "Telecom Billing"); Book subject : C++ Programming
strcpy( Book2.author, "YakitSingha"); Book id : 6495407
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700; Book title : Telecom Billing
// Print Book1 info Book author :YakitSingha
printBook( Book1 ); Book subject : Telecom
cout<<”\n\n”; Book id : 6495700
// Print Book2 info
printBook( Book2 );
}