STRUCTURES AND POINTERS

56
STRUCTURES AND POINTERS

description

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. THE COMPONENTS OF SUCH A VARIABLE CAN BE OF DIFFERENT TYPES (NON-HOMOGENEOUS). COMPONENTS ARE REFERENCED BY NAME. EXAMPLE:. - PowerPoint PPT Presentation

Transcript of STRUCTURES AND POINTERS

Page 1: STRUCTURES AND POINTERS

1

STRUCTURES

AND

POINTERS

Page 2: STRUCTURES AND POINTERS

2

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.

THE struct DATA TYPE

Page 3: STRUCTURES AND POINTERS

3

EXAMPLE:

TO REPRESENT INFORMATION ABOUT A STUDENT SUCH AS NAME, MAJOR, YEAR, AND GPA, SUCH A DATA struct MAY BE USED:

Page 4: STRUCTURES AND POINTERS

4

struct TYPE DEFINITION:

struct struct_type_name { type member_name_1; type member_name_2; ... type member_name_n; };

Page 5: STRUCTURES AND POINTERS

5

struct Student_Rec { char name[20]; char major[6]; char year; float gpa; };

Student_Rec student;

EXAMPLE: A STUDENT’S struct

Page 6: STRUCTURES AND POINTERS

6

student

Ist MEMBER: 2nd MEMBER: 3rd MEMBER: 4th MEMBER: name major year gpa

........ .......

Page 7: STRUCTURES AND POINTERS

7

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

Page 8: STRUCTURES AND POINTERS

8

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

EXAMPLE:

Page 9: STRUCTURES AND POINTERS

9

ASSUMING THE PREVIOUS struct DECLARATION AND THE FOLLOWING INPUT:

:Matthew P. Deek CIS 1 4.0

:

INPUT/OUTPUT OF struct VARIABLES

Page 10: STRUCTURES AND POINTERS

10

:

Get_Data(student);

:

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():

Page 11: STRUCTURES AND POINTERS

11

M A T T H E W P . D E E K \0 ? ? C I S \0 ? 1 4.0

student

MATTHEW’S struct

Page 12: STRUCTURES AND POINTERS

12

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

TO OUTPUT THE struct CONTENTS:

Page 13: STRUCTURES AND POINTERS

13

INDIRECT OUTPUT

:switch (student.year){case '1': cout << "FRESHMAN"; break;case '2': cout << "SOPHOMORE"; break;case '3': cout << "JUNIOR"; break;case '4': cout << "SENIOR";} :

Page 14: STRUCTURES AND POINTERS

14

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

Page 15: STRUCTURES AND POINTERS

15

IF cis101student AND cis113student WERE DECLARED

TO BE OF TYPE Student_Rec THEN:

cis101student = cis113student;

IS VALID.

Page 16: STRUCTURES AND POINTERS

16

THE PREVIOUS ASSIGNMENT IS EQUIVALENT TO:

strcpy(cis101student.name, cis113student.name);strcpy(cis101student.major, cis113student.major);cis101student.year = cis113student.year;cis101student.gpa = cis113student.gpa;

Page 17: STRUCTURES AND POINTERS

17

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.

ARRAYS WITH struct

COMPONENTS

Page 18: STRUCTURES AND POINTERS

18

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;

EXAMPLE:

Page 19: STRUCTURES AND POINTERS

19

student_list student_list[0].year

student_list[0]student_list[1] student_list[1].gpastudent_list[2] student_list[2].name

. . . . . .

student_list [MAX_STUDENTS-1] student_list[MAX_STUDENTS-1].major

Page 20: STRUCTURES AND POINTERS

20

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.

Page 21: STRUCTURES AND POINTERS

21

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.

Page 22: STRUCTURES AND POINTERS

22

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

FUNCTION Get_Info():

Page 23: STRUCTURES AND POINTERS

23

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;

NESTED STRUCTURES

Page 24: STRUCTURES AND POINTERS

24

person.birthday.year person.birthday.day person.birthday.month

......

person.name person.birthday

struct person

Page 25: STRUCTURES AND POINTERS

25

struct Personal_Data { char name[20]; int month, day, year; }; Personal_data person;

AN EQUIVALENT struct DEFINITION :

Page 26: STRUCTURES AND POINTERS

26

: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.

Page 27: STRUCTURES AND POINTERS

27

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

A FUNCTION TO INPUT Personal_Data FROM FILE person_in ONTO A person’S struct

(USING THE NESTED struct DECLARATION):

Page 28: STRUCTURES AND POINTERS

28

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

A FUNCTION TO INPUT Personal_Data FROM FILE person_in ONTO A person’S struct

(USING THE FLAT struct DECLARATION):

Page 29: STRUCTURES AND POINTERS

29

UNIONSIT IS OFTEN LOGICAL AND REALISTIC TO HAVE STRUCTURES IN WHICH COMPONENT TYPES AND MEMBERS DIFFER FROM

ONE struct TO THE OTHER.

Page 30: STRUCTURES AND POINTERS

30

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.

Page 31: STRUCTURES AND POINTERS

31

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

} };

Emoloyee_Data employee;

THE union DEFINITION:

Page 32: STRUCTURES AND POINTERS

32

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

Page 33: STRUCTURES AND POINTERS

33

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.

THE POINTER DATA TYPE

Page 34: STRUCTURES AND POINTERS

34

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.

MEMORY ALLOCATION

Page 35: STRUCTURES AND POINTERS

35

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.

STATIC VARIABLES

Page 36: STRUCTURES AND POINTERS

36

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.

DYNAMIC VARIABLES

Page 37: STRUCTURES AND POINTERS

37

struct Test_Score { float midterm, final; };typedef Test_Score *Test_Pointer;

Test_Pointer score_ptr, another_score_ptr;

POINTER TYPE DECLARATION:

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

Page 38: STRUCTURES AND POINTERS

38

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.

Page 39: STRUCTURES AND POINTERS

39

score_ptr POINTER VARIABLE OF TYPE AND Test_Pointeranother_score_ptr

*score_ptr REFERENCED VARIABLE

AND OF TYPE Test_Score*another_score_ptr

score_ptr->midterm THE DIFFERENT MEMBERS OF THEscore_ptr->final REFERENCED VARIABLE AND OF TYPE Test_Scoreanother_score_ptr->midtermanother_score_ptr->final

SYNTAX

Page 40: STRUCTURES AND POINTERS

40

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.

POINTER OPERATIONS

Page 41: STRUCTURES AND POINTERS

41

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.

Page 42: STRUCTURES AND POINTERS

42

*score_ptr

score_ptr ? ?

another_score_ptr ?

score_ptr POINTS TO A VARIABLE OF TYPE Test_Score (VALUE UNDEFINED).

another_score_ptr IS UNDEFINED.

Page 43: STRUCTURES AND POINTERS

43

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;

Page 44: STRUCTURES AND POINTERS

44

score_ptr->midterm

score_ptr 99.0 95.0

score_ptr->final

another_score_ptr ?

Page 45: STRUCTURES AND POINTERS

45

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.

Page 46: STRUCTURES AND POINTERS

46

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.

Page 47: STRUCTURES AND POINTERS

47

score_ptr 99.0 95.0

*score_ptr OR *another_score_ptranother_score_ptr

Page 48: STRUCTURES AND POINTERS

48

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."; :

Page 49: STRUCTURES AND POINTERS

49

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.

Page 50: STRUCTURES AND POINTERS

50

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.

Page 51: STRUCTURES AND POINTERS

51

EXAMPLE :

score_ptr = new Test_Score;score_ptr->midterm = 40.0;score_ptr->final = 35.0;

Page 52: STRUCTURES AND POINTERS

52

*another_score_ptr

another_score_ptr 99.0 95.0

score_ptr 40.0 35.0

*score_ptr

Page 53: STRUCTURES AND POINTERS

53

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

THE ASSIGNMENT STATEMENT:

:another_score_ptr = NULL; :

CAUSES THE FOLLOWING CHANGES:

Page 54: STRUCTURES AND POINTERS

54

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.

Page 55: STRUCTURES AND POINTERS

55

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.

Page 56: STRUCTURES AND POINTERS

56

another_score_ptr 99.0 95.0

POINTS TO NULL (ALLOCATION REMAINS, BUT WITH NO ACCESS TO THE VARIABLE)

score_ptr ?