1.24k likes | 2.77k Views
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:.
E N D
STRUCTURES AND POINTERS
THE structDATA 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: TO REPRESENT INFORMATION ABOUT A STUDENT SUCH AS NAME, MAJOR, YEAR, AND GPA, SUCH A DATA structMAY BE USED:
structTYPE DEFINITION: structstruct_type_name { typemember_name_1; type member_name_2; ... type member_name_n; };
EXAMPLE: A STUDENT’S struct struct Student_Rec { char name[20]; char major[6]; char year; float gpa; }; Student_Rec student;
student Ist MEMBER: 2nd MEMBER: 3rd MEMBER: 4th MEMBER:namemajoryeargpa ........ .......
ACCESSING structCOMPONENTS A structMEMBER IS SPECIFIED BY STATING THE NAME OF THE structVARIABLE AND THE NAME OF structMEMBER (WITH A PERIOD IN BETWEEN BOTH NAMES): struct_variable_name.member_name
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
INPUT/OUTPUT OF struct VARIABLES ASSUMING THE PREVIOUS structDECLARATION AND THE FOLLOWING INPUT: :Matthew P. Deek 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); :
M A T T H E W P . D E E K \0 ? ? C I S \0 ? 1 4.0 student MATTHEW’S struct
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:
: switch (student.year) {case '1': cout << "FRESHMAN"; break;case '2': cout << "SOPHOMORE"; break;case '3': cout << "JUNIOR"; break;case '4': cout << "SENIOR";} : INDIRECT OUTPUT
THE ASSIGNMENT STATEMENT AND structVARIABLES VALUES CAN BE ASSIGNED TO structMEMBERS, 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; :
IF cis101studentAND cis113studentWERE DECLARED TO BE OF TYPE Student_RecTHEN: cis101student = cis113student; IS VALID.
THE PREVIOUS ASSIGNMENT IS EQUIVALENT TO: strcpy(cis101student.name, cis113student.name); strcpy(cis101student.major, cis113student.major); cis101student.year = cis113student.year; cis101student.gpa = cis113student.gpa;
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
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:
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
EXAMPLE: ASSUME THAT A DISK FILEstudent_in CONTAINS INFORMATION ON EACH STUDENT IN CIS113 (THE STUDENT’S NAME, MAJOR, YEAR, AND GPA). THE FIRST structIN 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.
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.
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():
NESTED STRUCTURES A structCOMPONENT MAY ITSELF BE A struct. EXAMPLE: struct Date { int month, day, year; }; struct Personal_Data { char name[20]; Date birthday; }; Personal_data person;
person.birthday.year person.birthday.day person.birthday.month ...... person.name person.birthday struct person
AN EQUIVALENT struct DEFINITION : struct Personal_Data { char name[20]; int month, day, year; }; Personal_data person;
: 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.
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()
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()
UNIONS IT IS OFTEN LOGICAL AND REALISTIC TO HAVE STRUCTURES IN WHICH COMPONENT TYPES AND MEMBERS DIFFER FROM ONE structTO THE OTHER.
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.
THE unionDEFINITION: 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;
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");
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.
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.
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.
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.
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).
EXAMPLE: • score_ptr? • another_score_ptr? • score_ptrAND another_score_ptrARE UNDEFINED. THE DYNAMIC VARIABLES THAT THEY WILL POINT TO, WILL BE CREATED DURING PROGRAM EXECUTION.
SYNTAX 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->midtermTHE DIFFERENT MEMBERS OF THEscore_ptr->finalREFERENCED VARIABLE AND OF TYPE Test_Scoreanother_score_ptr->midtermanother_score_ptr->final
POINTER OPERATIONS AS WITH OTHER TYPES THERE ARE OPERATIONS DEFINED FOR VARIABLES OF TYPE POINTER. 1. THE newOPERATOR CREATES A DYNAMIC VARIABLE FOR THE POINTER TO POINT TO. THE newOPERATOR IS USED:score_ptr = new Test_Score; CREATES A VARIABLE OF TYPE Test_ScoreAND STORES ITS ADDRESS IN score_ptr.
THE newOPERATOR 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.
*score_ptr • score_ptr? ? • another_score_ptr? score_ptrPOINTS TO A VARIABLE OF TYPE Test_Score(VALUE UNDEFINED). another_score_ptrIS UNDEFINED.
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;
score_ptr->midtermscore_ptr 99.0 95.0score_ptr->final another_score_ptr ?
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.
SINCE BOTH score_ptrAND another_score_ptrARE 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_ptrTO BE DUPLICATED ONTO THE VARIABLE another_score_ptr.
score_ptr 99.0 95.0 *score_ptrOR *another_score_ptranother_score_ptr
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."; :
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.
4. POINTERVARIABLES 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. NULLCAN BE USED TO INDICATE THAT MEMORY HAS NOT BEEN ALLOCATED FOR THE DYNAMIC VARIABLE.NULLCANNOT BE USED TO DEALLOCATE A DYNAMIC VARIABLE’S MEMORY.