STRUCTURES AND POINTERS THE struct DATA TYPE A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN ENTITY.

Download Report

Transcript STRUCTURES AND POINTERS THE struct DATA TYPE A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN ENTITY.

STRUCTURES
AND
POINTERS
1
THE struct DATA TYPE
A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE
THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN
ENTITY. THE COMPONENTS OF SUCH A VARIABLE CAN BE
OF DIFFERENT TYPES (NON-HOMOGENEOUS).
COMPONENTS ARE REFERENCED BY NAME.
2
EXAMPLE:
TO REPRESENT INFORMATION ABOUT A STUDENT
SUCH AS NAME, MAJOR, YEAR, AND GPA, SUCH A
DATA struct MAY BE USED:
3
struct TYPE DEFINITION:
struct struct_type_name
{
type member_name_1;
type member_name_2;
...
type member_name_n;
};
4
EXAMPLE: A STUDENT’S struct
struct Student_Rec
{
char name[20];
char major[6];
char year;
float gpa;
};
Student_Rec student;
5
student
Ist MEMBER:
name
........
6
2nd MEMBER: 3rd MEMBER: 4th MEMBER:
major
year
.......
gpa
ACCESSING struct
COMPONENTS
A struct MEMBER IS SPECIFIED BY STATING THE NAME
OF THE struct VARIABLE AND THE NAME OF struct
MEMBER (WITH A PERIOD IN BETWEEN BOTH NAMES):
struct_variable_name.member_name
7
EXAMPLE:
student.year
TO REFERENCE THE 3rd MEMBER
student.name
TO REFERENCE THE 1st MEMBER
student.name[i]
TO REFERENCE A SPECIFIC
ELEMENT IN THE 1st MEMBER
student.gpa
TO REFERENCE THE 4th MEMBER
8
INPUT/OUTPUT OF struct
VARIABLES
ASSUMING THE PREVIOUS struct DECLARATION AND THE
FOLLOWING INPUT:
:
Matthew P. Deek
:
9
CIS 1 4.0
AN INPUT FUNCTION:
void Get_Data(Student_Rec &student)
{
cin.get(student.name, 20);
cin.get(student.major, 6);
cin >> student.year;
cin >> student.gpa;
return;
}
THE CALL TO THE FUNCTION Get_Data():
:
Get_Data(student);
:
10
M A T T H E W
P .
D E E K \0 ? ? C I S \0 ? 1 4.0
student
MATTHEW’S struct
11
TO OUTPUT THE struct CONTENTS:
void Put_Data(Student_Rec student)
{
cout << student.name << endl;
cout << student.major << endl;
cout << student.year << endl;
cout << student.gpa << endl;
return;
}
OR
:
cout << student.name << endl << student.major
<< endl << student.year << endl << student.gpa
<< endl;
12
:
:
switch (student.year)
{
case '1': cout << "FRESHMAN";
break;
case '2': cout << "SOPHOMORE";
break;
case '3': cout << "JUNIOR";
break;
case '4': cout << "SENIOR";
}
:
INDIRECT OUTPUT
13
THE ASSIGNMENT STATEMENT
AND struct VARIABLES
VALUES CAN BE ASSIGNED TO struct MEMBERS, AND ALSO
BETWEEN TWO VARIABLES OF THE SAME TYPE.
#include <string.h>
:
strcpy(student.name, "MATTHEW P. DEEK");
strcpy(student.major, "CIS");
student.year = '1';
student.gpa = 4.0;
:
14
IF cis101student AND cis113student WERE DECLARED
TO BE OF TYPE Student_Rec THEN:
cis101student = cis113student;
IS VALID.
15
THE PREVIOUS ASSIGNMENT IS EQUIVALENT TO:
strcpy(cis101student.name, cis113student.name);
strcpy(cis101student.major, cis113student.major);
cis101student.year = cis113student.year;
cis101student.gpa = cis113student.gpa;
16
ARRAYS WITH struct
COMPONENTS
WHEN DEALING WITH A LIST OF INFORMATION ON SEVERAL
ENTITIES (EACH CONSISTS OF MORE THAN ONE DATA ITEM),
AN ARRAY CAN BE USED WHERE EACH COMPONENT OF THE
ARRAY CONTAINS MULTIPLE VALUES.
17
EXAMPLE:
const int MAX_STUDENTS = 30;
struct Student_Rec
{
char name[20];
char major[6];
char year;
float gpa;
};
typedef Student_Rec Student_Array[MAX_STUDENTS];
Student_Array student_list;
18
student_list
student_list[0]
student_list[1]
student_list[2]
.
.
.
student_list[0].year
student_list[1].gpa
student_list[2].name
.
.
.
student_list
[MAX_STUDENTS-1]
student_list[MAX_STUDENTS-1].major
19
EXAMPLE:
ASSUME THAT A DISK FILE student_in CONTAINS
INFORMATION ON EACH STUDENT IN CIS113 (THE
STUDENT’S NAME, MAJOR, YEAR, AND GPA).
THE FIRST struct IN FILE student_in IS AN INTEGER
VALUE INDICATING HOW MANY STUDENT RECORDS
FOLLOW.
FUNCTION Get_Info() GETS THE DATA FROM THE FILE
AND STORES IT ONTO ARRAY student_list.
20
25<endl>
MATTHEW P. DEEK<endl>
CIS<endl>
1<endl>
4.0<endl>
ANDREW J. DEEK<endl>
CE<endl>
1<endl>
4.0<endl>
:
THE FIRST TWO RECORDS IN FILE student_in. EACH
student struct USES FOUR LINES. THE 1st LINE CONTAINS
THE NAME OF THE STUDENT, THE 2nd LINE CONTAINS
THE MAJOR, THE THIRD LINE CONTAINS THE YEAR AND
THE FOURTH LINE CONTAINS THE GPA.
21
FUNCTION Get_Info():
void Get_Info(Student_Array student_list)
{ // Get_Info()
int count, class_size;
char ch;
cin >> class_size;
for (count = 0; count < class_size; count ++)
{
cin.get(student_list[count].name, 20, '\n');
cin.get(ch);
// skip the end of line
cin >> student_list[count].major;
cin >> student_list[count].year;
cin >> student_list[count].gpa;
cin.get(ch);
// skip the end of line
}
// Get_Info()
22}
NESTED STRUCTURES
A struct COMPONENT MAY ITSELF BE A struct.
EXAMPLE:
struct Date
{
int month, day, year;
};
struct Personal_Data
{
char name[20];
Date birthday;
};
Personal_data person;
23
person.birthday.year
person.birthday.day
person.birthday.month
......
person.name
person.birthday
struct person
24
AN EQUIVALENT struct DEFINITION :
struct Personal_Data
{
char name[20];
int month, day, year;
};
Personal_data person;
25
:
ANDREW J. DEEK
:
4
28 1992<endl>
A struct IN FILE person_in. EACH person’S struct
USES ONE LINE WHICH CONTAINS THE NAME AND THE
BIRTHDAY DATE.
26
A FUNCTION TO INPUT Personal_Data FROM
FILE person_in ONTO A person’S struct
(USING THE NESTED struct DECLARATION):
void Get_Data(ifstream &person_in,
Personal_Data &person);
{ // Get_Data()
char ch;
if (!person_in.eof())
{
person_in.get(person.name, 20);
person_in >> person.birthday.month
>> person.birthday.day
>> person.birthday.year;
person_in.get(ch);
// skip the end of line
}
}; // Get_Data()
27
A FUNCTION TO INPUT Personal_Data FROM
FILE person_in ONTO A person’S struct
(USING THE FLAT struct DECLARATION):
void Get_Data(ifstream &person_in,
Personal_Data &person);
{ // Get_Data()
char ch;
if (!person_in.eof())
{
person_in.get(person.name, 20);
person_in >> person.month >> person.day
>> person.year;
person_in.get(ch);
// skip the end of line
}
}; // Get_Data()
28
UNIONS
IT IS OFTEN LOGICAL AND REALISTIC TO HAVE STRUCTURES
IN WHICH COMPONENT TYPES AND MEMBERS DIFFER FROM
ONE struct TO THE OTHER.
29
EXAMPLE:
THE CIS DEPARTMENT KEEPS INFORMATION ON ITS FACULTY
MEMBERS, STAFF, AND TEACHING ASSISTANTS.
FOR EACH, THERE IS A NAME, OFFICE NUMBER, PHONE
NUMBER AND EMPLOYMENT STATUS. IN ADDITION, FACULTY
MEMBERS RANK IS ALSO INDICATED; JOB TITLES FOR STAFF;
AND NO ADDITIONAL INFORMATION IS MAINTAINED FOR
TEACHING ASSISTANTS.
30
THE union DEFINITION:
enum Department_Member {FACULTY, STAFF, TA};
enum Rank_Type {ASSISTANTPROF, ASSOCIATEPROF,
FULLPROF};
struct Employee_Data
{ // the common section
char name[20];
int office_no;
char phone_no[13];
Department_Member status;
union
{ // the changeable section
Rank_Type rank; // faculty member only
char title[30]; // staff member only
// no such field for TA
}
};
31
Emoloyee_Data employee;
EXAMPLE:
strcpy(employee.name, "Rose M. G.");
employee.office_no = 4321;
strcpy(employee.phone_no, "201-123-4567");
employee.status = STAFF;
strcpy(employee.title,
"Department Secretary");
32
THE POINTER DATA TYPE
A POINTER VARIABLE CAN TAKE ON THE VALUES OF AN
ADDRESS IN MEMORY WHERE AN OBJECT RESIDES.
OBJECTS THAT POINTERS REFER TO ARE CALLED DYNAMIC
VARIABLES. SUCH VARIABLES ARE NOT DECLARED AND MAY
NOT EXIST UNTIL EXECUTION TIME.
33
MEMORY ALLOCATION
MEMORY ALLOCATION (FOR VARIABLES OF ALL TYPES
DISCUSSED SO FAR) TAKES PLACE BEFORE THE EXECUTION
OF THE CODE SEGMENT WHERE (THESE) VARIABLES ARE
USED. TO BE EXACT THE ALLOCATION TAKES PLACE DURING
COMPILE TIME. THIS IS REFERRED TO AS STATIC MEMORY
ALLOCATION.
MEMORY MAY BE ALLOCATED AND DEALLOCATED FROM
WITHIN THE CODE AND DURING EXECUTION TIME. THIS IS
CALLED DYNAMIC MEMORY ALLOCATION.
34
STATIC VARIABLES
WITH STATIC DATA TYPES, ONCE MEMORY IS ALLOCATED, THE
ALLOCATION REMAINS CONSTANT (IN SIZE) FOR THE
DURATION OF THE PROGRAM'S EXECUTION.
THE MEMORY LOCATIONS FOR LOCAL ENTITIES, HOWEVER,
ARE DESTROYED AS SOON AS THE EXECUTION OF MODULES
IS HALTED.
35
DYNAMIC VARIABLES
WITH DYNAMIC DATA TYPES, MEMORY CAN BE ALLOCATED
AND DEALLOCATED DURING THE PROGRAM EXECUTION. THIS
MEANS THAT STORAGE ALLOCATED BY A PROGRAM WOULD
BE TO THE EXACT SIZE AS NEEDED, AND MAY SHRINK AND
GROW APPROPRIATELY.
THIS ALLOWS FOR EFFICIENT RESOURCE MANAGEMENT.
36
POINTER TYPE DECLARATION:
struct Test_Score
{
float midterm, final;
};
typedef Test_Score *Test_Pointer;
Test_Pointer score_ptr, another_score_ptr;
score_ptr AND another_score_ptr ARE POINTERS
TO VARIABLES OF TYPE Test_Score. THIS DECLARATION
RESULTS IN THE ALLOCATION OF TWO MEMORY LOCATIONS
WHICH WILL CONTAIN MEMORY ADDRESSES (STILL
UNDEFINED).
37
EXAMPLE:
score_ptr
?
another_score_ptr
?
score_ptr AND another_score_ptr ARE UNDEFINED.
THE DYNAMIC VARIABLES THAT THEY WILL POINT TO, WILL BE
CREATED DURING PROGRAM EXECUTION.
38
SYNTAX
score_ptr
AND
another_score_ptr
POINTER VARIABLE OF TYPE
*score_ptr
REFERENCED VARIABLE
AND
*another_score_ptr
OF TYPE Test_Score
Test_Pointer
score_ptr->midterm
THE DIFFERENT MEMBERS OF THE
score_ptr->final
REFERENCED VARIABLE
AND
OF TYPE Test_Score
another_score_ptr->midterm
another_score_ptr->final
39
POINTER OPERATIONS
AS WITH OTHER TYPES THERE ARE OPERATIONS DEFINED FOR
VARIABLES OF TYPE POINTER.
1. THE new OPERATOR
CREATES A DYNAMIC VARIABLE FOR THE POINTER TO POINT
TO. THE new OPERATOR IS USED:
score_ptr = new Test_Score;
CREATES A VARIABLE OF TYPE Test_Score AND STORES ITS
ADDRESS IN score_ptr.
40
THE new OPERATOR WHEN APPLIED, INSTRUCTS THE
OPERATING SYSTEM’S MEMORY MANAGER TO
1) ALLOCATE AN AVAILABLE MEMORY LOCATION (THE SIZE
DEPENDS ON THE TYPE SPECIFIED AFTER THE new
OPERATOR).
2) STORE THE ADDRESS OF THE MEMORY LOCATION ONTO
THE POINTER VARIABLE, THEREFORE MAKING THE
POINTER VARIABLE POINT TO THE NEW LOCATION.
41
*score_ptr
score_ptr
?
another_score_ptr
?
?
score_ptr POINTS TO A VARIABLE OF TYPE Test_Score
(VALUE UNDEFINED).
another_score_ptr IS UNDEFINED.
42
2. ASSIGNMENTS
REFERENCED VARIABLES CAN BE USED IN THE SAME WAY AS
OTHER VARIABLES THAT IS CONSISTENT WITH ITS TYPE.
EXAMPLE:
score_ptr->midterm = 99.0;
score_ptr->final = 95.0;
43
score_ptr->midterm
score_ptr
99.0 95.0
score_ptr->final
another_score_ptr ?
44
THE VALUE OF A POINTER IS AN INTEGER (MEMORY
LOCATIONS HAVE ADDRESSES RANGING FROM ZERO TO
THE SIZE OF MEMORY-1). IT IS POSSIBLE TO MAKE
ASSIGNMENTS BETWEEN POINTERS OF THE SAME TYPE.
45
SINCE BOTH score_ptr AND another_score_ptr ARE
POINTERS TO THE struct VARIABLE Test_Score, THE
FOLLOWING ASSIGNMENT IS VALID.
another_score_ptr = score_ptr;
THE ASSIGNMENT STATEMENT CAUSES THE ADDRESS IN
score_ptr TO BE DUPLICATED ONTO THE VARIABLE
another_score_ptr.
46
score_ptr
99.0
95.0
*score_ptr OR
*another_score_ptr
another_score_ptr
47
3. POINTER VARIABLES OF THE SAME TYPE MAY BE TESTED
FOR EQUALITY OR INEQUALITY.
EXAMPLE:
:
if (score_ptr == another_score_ptr)
cout << "Both pointers are pointing to "
<< "the same location.";
:
48
OR
:
if (score_ptr != another_score_ptr &&
*score_ptr == *another_score_ptr)
cout << "Both pointers are not pointing to "
<< "the same location, but the values "
<< "at these locations are equal";
:
EQUALITY AND INEQUALITY ARE PERMISSIBLE RELATIONAL
OPERATIONS THAT CAN BE USED WITH THE TYPE POINTER.
49
4. POINTER VARIABLES MAY REFER TO A CONSTANT VALUE
CALLED NULL (DEFINED IN MANY HEADER FILES, e.g.
iostream.h, stdio.h, stdlib.h) WHICH DOES NOT
REPRESENT A MEMORY ADDRESS OF A DYNAMIC
VARIABLE.
NULL CAN BE USED TO INDICATE THAT MEMORY HAS NOT
BEEN ALLOCATED FOR THE DYNAMIC VARIABLE.
NULL CANNOT BE USED TO DEALLOCATE A DYNAMIC
VARIABLE’S MEMORY.
50
EXAMPLE :
score_ptr = new Test_Score;
score_ptr->midterm = 40.0;
score_ptr->final = 35.0;
51
*another_score_ptr
another_score_ptr
99.0
95.0
score_ptr
40.0
35.0
*score_ptr
52
THE ASSIGNMENT STATEMENT:
:
another_score_ptr = NULL;
:
CAUSES THE FOLLOWING CHANGES:
another_score_ptr
99.0 95.0
POINTS TO NULL (ALLOCATION REMAINS,
BUT WITH NO ACCESS
TO THE struct
VARIABLE)
score_ptr
40.0 35.0
*score_ptr
53
5. THE delete OPERATOR
DESTROYS A DYNAMIC VARIABLE POINTED TO BY THE
POINTER.
THE OPERATOR delete IS USED AS FOLLOWS:
delete score_ptr;
DESTROYS A VARIABLE OF TYPE Test_Score AND LEAVES
score_ptr UNDEFINED.
54
OPERATOR delete WHEN APPLIED, INSTRUCTS THE
OPERATING SYSTEM’S MEMORY MANAGER TO
1) CUT THE LINK BETWEEN THE POINTER AND THE DYNAMIC
VARIABLE.
2) DEALLOCATE THE MEMORY LOCATION AND RETURN IT
BACK TO POOL OF AVAILABLE SYSTEM MEMORY.
55
another_score_ptr
99.0 95.0
POINTS TO NULL (ALLOCATION REMAINS,
BUT WITH NO ACCESS TO
THE VARIABLE)
score_ptr
56
?