Sie sind auf Seite 1von 44

UNIT SEVEN

STRUCTURES
Structs
 C++ provides another structured data type, called a struct
(some languages use the term ‘‘record’’), to group related
items of different types.
 An array is a homogeneous data structure; a struct is typically
a heterogeneous data structure.
 A structure is a group of data elements grouped together
under one name. These data elements, known as members,
can have different types and different lengths
 Suppose that you want to write a program to process student
data.
 A student record consists of, among other things, the student’s
name, student ID, GPA, courses taken, and course grades.
 Thus, various components are associated with a student.
However, these components are all of different types.
 For example, the student’s name is a string and the GPA is a
floating-point number.
 Because these components are of different types, you
cannot use an array to group all of the items associated
with a student.
 C++ provides a structured data type called struct to
group items of different types.
 Grouping components that are related, but of different
types, offers several advantages.
 For example, a single variable can pass all the components
as parameters to a function.
 struct: A collection of a fixed number of components or
members in which the components are accessed by name.
 The components may be of different types.
 The components of a struct are called the members of the
struct.
Syntax
 The general syntax of a struct in C++ is:
struct structName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
dataType n identifiern;
};
 In C++, struct is a reserved word.
 The members of a struct, even though they are enclosed
in braces (that is, they form a block), are not considered
to form a compound statement.
 Thus, a semicolon (after the right brace) is essential to
end the struct statement.
 A semicolon at the end of the struct definition is,
therefore, a part of the syntax.
 Example: The statement:
struct employeeType
{
string firstName;
string lastName;
string address1;
string address2;
double salary;
string deptID;
};
defines a struct employeeType with six members.
 The members firstName, lastName, address1, address2,
and deptID are of type string, and the member salary is
of type double.
 Like any type definition, a struct is a definition, not a declaration.
 That is, it defines only a data type; no memory is allocated.
 Once a data type is defined, you can declare variables of that type.
 Let us see the following example, first define a struct type,
studentType, and then declare variables of that type by the name
newStudent and student:
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
};
//variable declaration
studentType newStudent;
studentType student;
 The above statements declare two struct variables,
newStudent and student, of type studentType.
 The memory allocated is large enough to store
firstName, lastName, courseGrade, testScore,
programmingScore, and GPA (see Figure 7-1). below

FIGURE 7-1 struct newStudent and student


 Note: You can also declare struct variables when you
define the struct. For example, consider the following
statements:
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
} tempStudent;
 These statements define the struct studentType and also
declare tempStudent to be a variable of type studentType.
 Typically, in a program, a struct is defined before the
definitions of all the functions in the program, so that the
struct can be used throughout the program.
 Therefore, if you define a struct and also simultaneously
declare a struct variable (as in the preceding statements),
then that struct variable becomes a global variable and
thus can be accessed anywhere in the program.
 Keeping in mind the side effects of global variables, you
first should only define a struct and then declare the
struct variables.
 We can also declare the structure objects mother, father
and spouse at the moment we define the structure like this
way: struct person{
float height;
int eye_color; char name[20];
 This sets up a structure called person and declares three
variables of that type.
 Each of these people will have a name, a height and an eye
color.
 The declaration does not set up these values - they start off as
random values and characters, whatever happens to be in
the memory allocated at the time.
 The data is set up as follows:
friend.name = "Diane";
friend.eye_colour = 1;
friend.height = 1.61; 
mother.name = "Mary";
mother.eye_colour = 2;
mother.height = 1.44; 
spouse.name = "Helen";
spouse.eye_colour = 1;
spouse.height = 1.7;
After the data is set up using assignment statement and
variables.members to access the members, it is as
follows.
Example 1
 Let’s see the following simple program to demonstrate structure
by defining the struct type of student and with variable
declaration of stud1:
//Program to implement structure definition and
//Variable declaration of that struct type
#include<iostream.h>
#include<conio.h>
struct student
{
char id_num[11];
char name [20];
int age ;
};
void main ( )
{
clrscr( );
student stud1;
cout<<"Enter id number: ";
cin>>stud1.id_num;
cout<<"Enter name of the student: ";
cin>> stud1.name;
cout<<"Enter age: ";
cin>>stud1.age;
cout<<“ Id Number is : "<<stud1.id_num<<“\n”;
cout<<“ Name of student is : "<<stud1.name<<“\n”;
cout<<“ Age of the student is: "<<stud1.age<<“\n”;
getch( );
}
 In the above program, the structure student has 3 data
items called members: id-num , name, and age.
 The keyword struct is followed by the structure name
student members of the structure are enclosed with in
braces, and this is a semicolon at the end of the brace
(unlike braces delimiting blocks of codes in loops and
decisions).
 In the main ( ) function , a variable declaration called
stud1 of type structure student is defined.
 This definition is the same as other types of variable
definition of in built data like int, char, etc.
 But here, the data type is user defined.
 We can define as many variables of type structure student
as possible, like stud2, stud3, etc.
Accessing struct Members
 In arrays, you access a component by using the array
name together with the relative position (index) of the
component.
 The array name and index are separated using square
brackets.
 The syntax for accessing a struct member is:
structVariableName.memberName;
 The structVariableName.memberName is just like any
other variable.
 Once we have declared our three variables of a determined
structure type product(for example; apple, banana and
melon) we can operate directly with their members.
 To do that we use a dot (.) operator between the
variable name and the member name.
 For example, we could operate with any of these
elements as if they were standard variables of their
respective types:
apple.weight
apple.price
banana.weight
banana.price
melon.weight
melon.price
 Each one of these has the data type corresponding
to the member they refer to.
Example 2
#include <iostream.h>
#include <string.h>
#include <conio.h>
struct movies_t {
char title [60];
int year;
} mine, yours;

void printmovie(movies_t movie);

int main ()
{
strcpy(mine.title,"2001 A Space Odyssey");
mine.year = 1968;
cout<< "Enter your favorite Film title: \n";
cin.get (yours.title,60);
cout<< "Enter year: \n";
cin>>yours.year;
cout<< "\n My favorite movie is:\n ";
printmovie (mine);
cout<< "And yours is:\n ";
printmovie (yours);
return 0;
}

void printmovie (movies_t movie) {


cout << movie.title;
cout << " (" << movie.year << ")\n";
}
 The example shows how we can use the members of a
variable as regular variables.
 For example, the member yours. year is a valid variable
of type int, and mine.title is a valid variable of type string.
 The variables mine and yours can also be treated as valid
variables of type movies_t, for example we have passed
them to the function printmovie as we would have done
with regular variables.
 Therefore, one of the most important advantages of data
structures is that we can either:
 Refer to their members individually or
 Refer to the entire structure as a block with only one
identifier.
Initializing structure variables
 It is possible to give values to the structure members at the
point of definition like the following.
#include<iostream.h>
#include<conio.h>
const int NAME = 25;
const int ID = 11;
struct student
{
char name [NAME];
char id_num[ID];
int age;
};
void main ( )
{
clrscr( );
student stud1= { "Alem ", "019/97",25};
student stud2;
stud2= stud1;
cout<<"Name at global is:"<<NAME<<"\n";
cout<<"ID at global is: "<<ID<<"\n";
cout<<"Name:"<<stud1.name<<"\n";
cout<<"ID: " <<stud1.id_num<<"\n";
cout<<"\n Copied data from variable stud1 to stud2"<<endl;
cout<<"Name of the student is:"<<stud2.name<<"\n";
cout<<"Id number of the students is: <<stud2.id_num<<"\n";
cout<<"Age:"<<stud2.age;
getch ( );
}
 In this program, we initialized the name, id_num and age
members of the student variable type sud1.
 Note that we initialize values based on the order of the
variables in the structure specification of student, first
for name, then for id, then age another feature.
 we use the assignment operator to assign the value of
each member of stud1 to the corresponding member of
stud2.
 This type of assignment is possible only if the two
structure variables are the same type (in the above case,
both are of same type student). 
 Another thing you should note in this program is the use
of the global constant NAME and ID.
 They can be used both in the structure and in main, and
hence they are called global.
Member functions
 One of the most important features of the C++ structure is member
functions.
 Each data type can have its own built-in functions.
 Let see the following simple example to implement that the person
type structure in which each data type has its own built-in function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
struct person {
string name[20];
int age;
//of course, member variables must be present
void print() {
cout<<name<<";"<<age<<endl;
//we don't have to mention what "name" and "age" are,
//because it automatically refers back to the
//member variables
}
};
int main () {
clrscr ();
person a, b;
a.name="Wales";
b.name="Jones";
a.age = 30;
b.age = 20;
cout<<a.name<<": "<<a.age<<endl;
cout<< b.name<<": "<<b.age<<endl;
a.print();
b.print();  a and b above are called senders, and each of
return 0; them will refer to their own member variables
} when the print() function is executed.
Arrays in structs
 A list is a set of elements of the same type. Thus, a list has
two things associated with it: the values (that is,
elements) and the length.
 Because the values and the length are both related to a
list, we can define a struct containing both items.
const int ARRAY_SIZE = 1000;
struct listType
{
int listElem[ARRAY_SIZE]; //array containing the list
int listLength; //length of the list
};
 The following statement declares intList to be a struct
variable of type listType (see Figure7-5):
listType intList;
FIGURE 7-5 struct variable intList
 The variable intList has two members: listElem, an array of 1000
components of type int;and listLength,oftype int.
 Moreover, intList.listElem accesses the member listElem and
intList.listLength accesses the member listLength.
 Consider the following statements:
intList.listLength = 0; //Line 1
intList.listElem[0] = 12; //Line 2
intList.listLength++; //Line 3
intList.listElem[1] = 37; //Line 4
intList.listLength++; //Line 5
 The statement in Line 1 sets the value of the member listLength to 0.
The statement in Line 2 stores 12 in the first component of the array
listElem.
 The statement in Line 3 increments the value of listLength by 1.
 The meaning of the other statements is similar. After these
statements execute, intList is as shown in Figure 7-6.
FIGURE 7-6 intList after the statements in Lines 1 through 5 execute
Example 3: Array of structures
#include <iostream.h>
#include <stdlib.h>
#define N_MOVIES 5
struct movies_t {
char title[50] ;
int year;
} films [N_MOVIES] ;
void printmovie(movies_t movie);
int main () {
char buffer [50] ;
int n;
for(n=0 ; n<N_MOVIES; n++) {
cout<< "Enter title: ";
cin.getline(films [n] . title,50);
cout << "Enter year: " ;
cin.getline (buffer, 50);
films[n].year =atoi(buffer);
}
cout << "\n you have entered these movies :\n";
for(n=0; n<N_MOVIES; n++)
printmovie(films[ n]);
return 0 ;
}
void printmovie(movies_t movie) {
cout << movie. title;
cout << " ( " << movie.year << ") \n";
}
Pointers to Structures
 Like any other type, structures can be pointed by pointers.
The rules are the same as for any fundamental data type:
 The pointer must be declared ad a pointer to the structure:
struct movies_t{
char title [50];
int year;
};
movies_t amovie;
movies_t*pmovie;
 Here amovie is an object of struct type movies_t and pmovie
is a pointer to point to objects of struct type movies_t.
 So, the following, as with fundamental types, would also be
valid. pmovie = &amovie;
 Ok, we will now go with another example, that will serve us
to introduce a new operator:
Example 4
//program to implement pointers to structure
#include<iostream.h>
#include<stdlib.h>
struct movies_t{
char title [50];
int year;
};
int main ()
{
char buffer [50];
movies_t amovie;
movies_t*pmovie;
pmovie=&amovie;
cout<<"Enter title:";
cin.getline (pmovie->title,50);
cout<< "Enter year:";
cin.getline(buffer, 50);
pmovie->year=atoi (buffer);
cout<< "\n you have entered:\n";
cout<<pmovie->title;
cout<<"("<<pmovie->year<<")\n";
return 0;
}
The previous code includes a new 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.
pmovie->title
that could be translated to:
(*pmovie).title
both expressions pmovie->title and (*pmovie).title are valid
and mean that we are evaluating the element title of the
structure pointed by pmovie.
You must distinguish it clearly from:
*pmovie.title
that is equivalent to
*(pmovie.title)
and that would serve to evaluate the value pointed by
element title of structure movies that in this case (where
title is not a pointer) it would not make much sense.
 The following panel summarize possible combinations of
pointers and structures:
Expression Description

pmovie . title elemet title of structu pmovie

pmovie-> title element title of structure pointed by


pmovie (*pmovie).title

*pmovie.titile value pointed by element title of


structure pmovie*(pmovie.title)
Nesting Structures
 Structures can also be netted so that a valid element of
structure can also be another structure.
 Let see the following example to demonstrated nesting
structures.
#include <conio.h>
#define STR 30
struct address {
char street [STR];
char post ;
float distance ; //in kilometers
};
struct employee {
address branch;
address home ;
};
void main( )
{
clrscr ( );
employee emp1;
cout<<"Enter branch street of the employee:";
cin.get(emp1.branch.street[STR]);
cout<<"Enter branch post address"<<endl;
cin>>emp1.branch.post;
cout<<"Enter distance of the branch"<<endl;
cin>>emp1.branch.distance;
cout<<"Employee's branch street
is :"<<emp1.branch.street[STR]<<"="<<endl;
cout<<"and it is "<<emp1.branch.distance << "kms Away ";
getch( );
}
Structures in structures in Structures
 Structures may be used inside other structures . Let’s see the
following program to demonstrate structures in structures in
structures
#include<iostream.h>
#include<string.h>
main() {
struct dateSturct{
int day; //the day of a date
int mont; // the month of a date
int year; //the year of a date
};
struct student {
char name [40];
dateSturct birthdate;//date of a student's birth
int grades[5];//student's test grades
};
struct classRoll{
student roll[50];//currently enrolled students in class
int testsGiven;//number of tests the students have taken
int size;// nuber of students enrolled
};
classRoll csc114;//the class information for csc114
strcpy (csc114.roll[0].name,"carol Miller");
csc114.roll[0].birthdate.day=17;
csc114.roll[0].grades[3]=23;
csc114.testsGiven=3;
}
Relation between CLASS and Structures
 Classes at their simplest are slightly related to the word
old srtuct.
 In fact if you wanted to use a class instead of struct but
don’t want to have to change any of your code you could
do what do to the date sturct (below)
sturct date
{
int year, month, day;
};
 And make it look something like:
class date
{
Public:
int year, month ,day;
 Of course this is blasphemous coding and if any stick –
up-the ass c++ programmer catches you doing this then
he’ll have your head.
 But for our purposes this will do just fine and ill build on
the above example in the succeeding parts.
 If you don’t know how to declare a structure type or
know how to use a structure variable then please get to
that first. Let’s see the following example:
class number {
public :
int i;
void output();
};
 In the above example, number is the name of the new
class being created.
 This class contains number in the form of an integer.
 To output the number, the output procedure is cells using
the standard”,” notation.
 Since the function is defined as part of the class, ti has
access to all the date items defined in the class, hence it
can read or write to i.
 The function definition itself can appear outside the class
with the function name preceded by the class name and
“::” to indicate that it is a member of that class and not a
global function .
 Let’s see the following another simple example:
void Number::Output()\
{
printf(“%u”, i);
}
Number aNumber;
aNumber.i=12
aNumber.Output();
Objects are normal data types in every sense.
 Thus the can be used in functions for parameters and
return values.
They can be crated/ deposed using pointer. Just likes
structs, scope is an important consideration.
All the names used within an class are local to that class
only the class name it self is global.
Exercise 
 Write a program using structure which accepts
information on five books. The information includes title
of the book, and publication year. There is another
information about the book, called status, status will
automatically be given by the program based on the
publication year entered by the user, if year of put
publication is before 1990, the status is “Out dated”; it
the book is published between 1991-2000, the status will
automatically be “medium”, for books published after the
year 2000, status will be “latest”, the program should
output what is entered by the user in the following ways
as an example.
title:
publication year:
status:

Das könnte Ihnen auch gefallen