Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.

Slides:



Advertisements
Similar presentations
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Chapter Objectives You should be able to describe: Assignment Pointers as Class Members Additional Class Features Common Programming Errors.
Chapter 10.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
C++ for Engineers and Scientists Third Edition
Chapter 6: Functions.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CNG 140 C Programming (Lecture set 10) Spring Chapter 12 Structures.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
計算機程式語言 Lecture 13-1 國立臺灣大學生物機電系 13 Structures.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Chapter 3: Assignment, Formatting, and Interactive Input.
Structures Combining data types into a logical groupings.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Engineering Problem Solving with C Fundamental Concepts Chapter 7 Structures.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
Structures - Part II aggregate operations arrays of type struct nested structures compared to classes.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Review 1 List Data Structure List operations List Implementation Array Linked List.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Programming Fundamentals1 Chapter 6 FUNCTIONS AND POINTERS.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Pointers and Arrays Dynamic Variables and Arrays.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Objectives You should be able to describe: One-Dimensional Arrays
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
© 2016 Pearson Education, Ltd. All rights reserved.
Pointer Data Type and Pointer Variables II
Chapter 10: Pointers 1.
Objectives You should be able to describe: Addresses and Pointers
Arrays Arrays A few types Structures of related data items
Presentation transcript:

Chapter 11 Structure

2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure Allocation Common Programming Errors

3 Structures Arrays make it possible to access list of data of same data type using single variable name Need different mechanism to store information of varying types in one data structure –Mailing list data –Parts inventory data

4 Structures (continued) Structure: Data structure that stores different types of data under single name –A structure is class that has no methods –All variables of class are public (default) –Example: Figure 11.2 Creating and using a structure requires two steps: –Declaration –Assigning values

5 Structures (continued)

6 Structure declaration: List the data types, data names and arrangements of data items Example: Birth structure consists of three data items or fields called structure members struct { int month; int day; int year; } birth;

7 Structures (continued) Populating the structure: Assigning data values to data items of a structure –Data structure members accessed by giving the structure name and individual data item name separated by period Period called member access operator (dot operator) Example: birth.month refers to the first member of birth structure –Program 11.1 assigns values to individual members of birth structure

8 Structures (continued)

9 Output produced by program 11.1: My Birth date is 12/28/86 Format of structure definition is flexible: The following is valid struct {int month; int day; int year;} birth; Multiple variables can be declared in the same statement struct {int month; int day; int year;} birth, current; –Creates two structures of the same form birth.day, birth.month, birth.year current.day, current.month, current.year

10 Structures (continued) Modified format for defining structures struct Date { int month; int day; int year; }; –Date: Structure type name that defines new data type that is a data structure of above form –Definition statement: Date birth, current; Reserves storage for two date structure variables named birth and current Example: Program 11.2 illustrates declaration of a Date data type

11 Structures (continued)

12 Structures (continued) Initialization of structures: Follows same rules as initialization of arrays –Global and local structures initialized by following the definition with list of initializers –Example: date birth = {12, 28, 86} can replace first four statements in main() in Program 11.2 Individual members of structure not limited to one data type –Can be any valid C++ data type including both arrays and structures

13 Arrays of Structures Real power of structures realized when same structure is used for lists of data Example: Process employee data in Figure 11.3 –Option 1: Consider each column in Figure 11.3 as a separate list, stored in its own array Employee numbers stored in array of integers Names stored in array of strings Pay rate stored in array of double-precision numbers Correspondence between items for individual employee maintained by storing employee’s data in same array position in each array

14 Arrays of Structures (continued)

15 Arrays of Structures (continued) Option 1 is not a good choice –Items related to single employee constitute a natural organization of data into structures Better option: Use structure shown in Figure 11.4 –Data can be processed as single array of ten structures –Maintains integrity of the data organization as a record

16 Arrays of Structures (continued)

17 Arrays of Structures (continued) Declaring an array of structures: Same as declaring an array of any other variable type –If data type PayRecord is declared as: struct PayRecord { int idNum; string name; double rate: }; –An array of ten such structures can be defined as: PayRecord employee[10];

18 Arrays of Structures (continued) Referencing an item in an array of structures: employee[0].rate refers to rate member of the first employee structure in employee array Including structures as elements of array makes it possible to process list of structures using standard array programming techniques Program 11.3 displays first five employee records illustrated in Figure 11.4

19 Structures as Function Arguments Individual structure members are passed to a function in same manner as a scalar variable Example: Given the structure definition struct { int idNum; double payRate; double hours; } emp; the statement display (emp.idNum); passes a copy of the structure member emp.idNum to a function named display()

20 Structures as Function Arguments (continued) Passing complete copies of all members of structure to a function –Include name of structure as argument Example: The function call calcNet(emp); passes a copy of the complete emp structure to calcNet() –A declaration must be made to receive structure

21 Structures as Function Arguments (continued) Example: Program 11.4 declares a global data type for Employee structure This type is then used by both main() and calcNet() functions to define specific structures with names emp and temp The output produced by Program 11.4 is The net pay for employee 6782 is $361.66

22 Structures as Function Arguments (continued)

23 Structures as Function Arguments (continued)

24 Structures as Function Arguments (continued) In Program 11.4, both main() and calcNet() use the Employee data type The variables defined in main() and calcNet() are different structures –Changes to local temp variable in calcNet() are not reflected in emp variable of main() Same structure variable name could have been used in both functions with no ambiguity –Both structure variables are local to their respective functions

25 Passing a Pointer Using a pointer requires modifications to Program 11.4: –Call to calcNet() : calcNet(&emp); –calcNet() function definition: calcNet(Employee *pt) Example: Program 11.4a –Declares pt as a pointer to structure of type Employee –pt receives starting address of structure whenever calcNet() is called –calcNet() uses pt to access members of structure

26 Passing a Pointer (continued) Example: Program 11.4a –(*pt).idNum refers to idNum member –(*pt).payRate refers to payRate member –(*pt).hours refers to hours member –These relationships illustrated in Figure 11.5 –Parentheses around the expression *pt in Figure 11.5 are necessary to initially access “the structure whose address is in pt ”

27 Passing a Pointer (continued)

28 Passing a Pointer (continued) Starting address of emp is also address of first member of the structure (Figure 11.5) Special notation commonly used –Expression (*pointer).member can always be replaced with notation pointer->member –The following expressions are equivalent: (*pt).idNum can be replaced by pt->idNum (*pt).payRate can be replaced by pt->payRate (*pt).hours can be replaced by pt->hours

29 Passing a Pointer (continued) Program 11.5 illustrates passing structure’s address –Uses a pointer with -> notation to reference structure directly When calcNet() is called with statement netPay = calcNet(&emp); emp ’s starting address is passed to the function Using this address as starting point, individual members of structure are accessed by including their names with pointer emp -> hours

30 Passing a Pointer (continued) Incrementing or decrementing a pointer: Use increment or decrement operators –Expression ++pt->hours; adds one to hours member of emp structure –-> operator has higher priority than increment operator, therefore hours member is accessed first, then increment is applied –Expression (++pt)->hours; increments address before hours member is accessed –Expression (pt++)->hours; increments address after hours member is accessed

31 Passing a Pointer (continued) #include using namespace std; struct Employee // declare a global type { int idNum; double payRate; double hours; }; double calcNet(Employee *); //function prototype int main() { Employee emp = {6782, 8.93, 40.5}; double netPay;

32 Passing a Pointer (continued) netPay = calcNet(&emp); // pass an address // set output formats cout << setw(10) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2); cout << "The net pay for employee " << emp.idNum << " is $" << netPay << endl; return 0; } double calcNet(Employee *pt) // pt is a pointer to a { // structure of Employee type return (pt->payRate * pt->hours); }

33 Passing a Pointer (continued) Example (Fig 11.6): Array of three structures of type employee with address of emp[1] stored in the pointer variable pt –Expression ++pt changes address in pt to starting address of emp[2] –Expression --pt changes address in pt to starting address of emp[0]

34 Passing a Pointer (continued)

35 Returning Structures Structure handling functions receive direct access to structure by receiving structure reference or address –Equivalent to pass by reference –Changes to structure made in function Functions can also return separate structure –Must declare function appropriately and alert calling function to type of data being returned

36 Dynamic Structure Allocation Dynamic allocation of memory especially useful for lists of structures –Permits lists to expand and contract as records are added or deleted Additional storage space: Use new operator and indicate amount of storage needed –Expression new(int) or new int requests enough space to store integer number

37 Dynamic Structure Allocation (continued)

38 Dynamic Structure Allocation (continued) Dynamically requesting storage for a structure: –If structure has been declared as follows: struct TeleType { string name; string phoneNo; }; –Expressions new(TeleType) or new TeleType reserve storage for one TeleType structure Program 11.7 illustrates use of new to dynamically create a structure in response to user input request

39 Dynamic Structure Allocation (continued) Example: Program 11.7 –Two variables declared in main() key declared as a character variable recPoint declared as pointer to structure of the TeleType type –If user enters y in response to first prompt in main(), a call to new is made for memory to store structure –Address loaded into recPoint can be used to access newly created structure

40 Dynamic Structure Allocation (continued) Example: Program 11.7 –The function populate() prompts user for data to fill structure The argument passed to populate() in main() is pointer recPoint –The disOne() function displays contents of newly created and populated structure Address passed to dispOne() is same address that was passed to populate()

41 Common Programming Errors Trying to use a structure, as a complete entity, in a relational expression –Individual members of structure can be compared, but not entire structure Using pointer in relation to structure and not indicating proper data type

42 Summary A structure allows individual variables to be grouped under common variable name A data type can be created from structure by using declaration form struct Data-type { individual member declarations; }; –Individual structure variables may then be defined as this data type

43 Summary (continued) Structures are useful as elements of arrays Complete structures can be function arguments –Called function receives copy of each element in structure –The address of structure may also be passed, either as reference or as pointer Structure members can be any C++ data type, including other structures, arrays, and pointers