Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Similar documents
Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Pointers and Dynamic Arrays

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

Lecture 1: Introduction and Strassen s Algorithm

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS 11 C track: lecture 1

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

The Implementation of Data Structures in Version 5 of Icon* Ralph E. Gr is wo Id TR 85-8

CMPT 125 Assignment 2 Solutions

Ones Assignment Method for Solving Traveling Salesman Problem

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Python Programming: An Introduction to Computer Science

From last week. Lecture 5. Outline. Principles of programming languages

The Magma Database file formats

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

condition w i B i S maximum u i

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Python Programming: An Introduction to Computer Science

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

The isoperimetric problem on the hypercube

Algorithm. Counting Sort Analysis of Algorithms

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

Examples and Applications of Binary Search

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Analysis of Algorithms

Computers and Scientific Thinking

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

On Infinite Groups that are Isomorphic to its Proper Infinite Subgroup. Jaymar Talledo Balihon. Abstract

Bezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only

CIS 121. Introduction to Trees

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

n Haskell n Syntax n Lazy evaluation n Static typing and type inference n Algebraic data types n Pattern matching n Type classes

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

6.854J / J Advanced Algorithms Fall 2008

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

1.2 Binomial Coefficients and Subsets

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

Lecture 5. Counting Sort / Radix Sort

One advantage that SONAR has over any other music-sequencing product I ve worked

Behavioral Modeling in Verilog

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Math Section 2.2 Polynomial Functions

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

Pattern Recognition Systems Lab 1 Least Mean Squares

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Data Structures and Algorithms. Analysis of Algorithms

Counting Regions in the Plane and More 1

EE 459/500 HDL Based Digital Design with Programmable Logic. Lecture 13 Control and Sequencing: Hardwired and Microprogrammed Control

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

top() Applications of Stacks

. Written in factored form it is easy to see that the roots are 2, 2, i,

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Big-O Analysis. Asymptotics

What have we learned about when we learned about function parameters? 1-1

NTH, GEOMETRIC, AND TELESCOPING TEST

EE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

Evaluation scheme for Tracking in AMI

Homework 1 Solutions MA 522 Fall 2017

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

Inductive Definition to Recursive Function

CS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018

CSE 417: Algorithms and Computational Complexity

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

Schema for the DCE Security Registry Server

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Combination Labelings Of Graphs

Module 8-7: Pascal s Triangle and the Binomial Theorem

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

MR-2010I %MktBSize Macro 989. %MktBSize Macro

The Adjacency Matrix and The nth Eigenvalue

3D Model Retrieval Method Based on Sample Prediction

Transcription:

Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3

9.1 Poiters Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

Poiters A poiter is the memory address of a variable Memory addresses ca be used as ames for variables If a variable is stored i three memory locatios, the address of the first ca be used as a ame for the variable. Whe a variable is used as a call-by-referece argumet, its address is passed Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-5

Poiters Tell Where To Fid A Variable A address used to tell where a variable is stored i memory is a poiter Poiters "poit" to a variable by tellig where the variable is located Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-6

Declarig Poiters Poiter variables must be declared to have a poiter type Example: To declare a poiter variable p that ca "poit" to a variable of type double: double *p; The asterisk idetifies p as a poiter variable Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-7

Multiple Poiter Declaratios To declare multiple poiters i a statemet, use the asterisk before each poiter variable Example: it *p1, *p2, v1, v2; p1 ad p2 poit to variables of type it v1 ad v2 are variables of type it Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-8

The address of Operator The & operator ca be used to determie the address of a variable which ca be assiged to a poiter variable Example: p1 = &v1; p1 is ow a poiter to v1 v1 ca be called v1 or "the variable poited to by p1" Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-9

The Dereferecig Operator C++ uses the * operator i yet aother way with poiters The phrase "The variable poited to by p" is traslated ito C++ as *p Here the * is the dereferecig operator p is said to be derefereced Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-10

A Poiter Example v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << edl; cout << *p1 << edl; v1 ad *p1 ow refer to the same variable output: 42 42 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-11

Poiter Assigmet The assigmet operator = is used to assig the value of oe poiter to aother Example: If p1 still poits to v1 (previous slide) the p2 = p1; causes *p2, *p1, ad v1 all to ame the same variable Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-12

Cautio! Poiter Assigmets Some care is required makig assigmets to poiter variables p1= p3; // chages the locatio that p1 "poits" to *p1 = *p3; // chages the value at the locatio that // p1 "poits" to Display 9.1 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-13

The ew Operator Usig poiters, variables ca be maipulated eve if there is o idetifier for them To create a poiter to a ew "ameless" variable of type it: p1 = ew it; The ew variable is referred to as *p1 *p1 ca be used ayplace a iteger variable ca ci >> *p1; *p1 = *p1 + 7; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-14

Dyamic Variables Variables created usig the ew operator are called dyamic variables Dyamic variables are created ad destroyed while the program is ruig Additioal examples of poiters ad dyamic variables are show i Display 9.2 A illustratio of the code i Display 9.2 is see i Display 9.3 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-15

ew ad Class Types Usig operator ew with class types calls a costructor as well as allocatig memory If MyType is a class type, the MyType *myptr; // creates a poiter to a // variable of type MyType myptr = ew MyType; // calls the default costructor myptr = ew MyType (32.0, 17); // calls Mytype(double, it); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-16

Basic Memory Maagemet A area of memory called the freestore or the heap is reserved for dyamic variables New dyamic variables use memory i the freestore If all of the freestore is used, calls to ew will fail Ueeded memory ca be recycled Whe variables are o loger eeded, they ca be deleted ad the memory they used is retured to the freestore Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-17

The delete Operator Whe dyamic variables are o loger eeded, delete them to retur memory to the freestore Example: delete p; The value of p is ow udefied ad the memory used by the variable that p poited to is back i the freestore Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-18

Daglig Poiters Usig delete o a poiter variable destroys the dyamic variable poited to If aother poiter variable was poitig to the dyamic variable, that variable is also udefied Udefied poiter variables are called daglig poiters Dereferecig a daglig poiter (*p) is usually disasterous Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-19

Automatic Variables Variables declared i a fuctio are created by C++ ad destroyed whe the fuctio eds These are called automatic variables because their creatio ad destructio is cotrolled automatically The programmer maually cotrols creatio ad destructio of poiter variables with operators ew ad delete Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-20

Global Variables Variables declared outside ay fuctio defiitio are global variables Global variables are available to all parts of a program Global variables are ot geerally used Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-21

Type Defiitios A ame ca be assiged to a type defiitio, the used to declare variables The keyword typedef is used to defie ew type ames Sytax: typedef Kow_Type_Defiitio New_Type_Name; Kow_Type_Defiitio ca be ay type Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-22

Defiig Poiter Types To avoid mistakes usig poiters, defie a poiter type ame Example: typedef it* ItPtr; ItPtr p; Defies a ew type, ItPtr, for poiter variables cotaiig poiters to it variables is equivalet to it *p; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-23

Multiple Declaratios Agai Usig our ew poiter type defied as typedef it* ItPtr; Prevet this error i poiter declaratio: it *P1, P2; // Oly P1 is a poiter variable with ItPtr P1, P2; // P1 ad P2 are poiter // variables Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-24

Poiter Referece Parameters A secod advatage i usig typedef to defie a poiter type is see i parameter lists Example: void sample_fuctio(itptr& poiter_var); is less cofusig tha void sample_fuctio( it*& poiter_var); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-25

Sectio 9.1 Coclusio Ca you Declare a poiter variable? Assig a value to a poiter variable? Use the ew operator to create a ew variable i the freestore? Write a defiitio for a type called NumberPtr to be a type for poiters to dyamic variables of type it? Use the NumberPtr type to declare a poiter variable called my_poit? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-26

9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

Dyamic Arrays A dyamic array is a array whose size is determied whe the program is ruig, ot whe you write the program Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-28

Poiter Variables ad Array Variables Array variables are actually poiter variables that poit to the first idexed variable Example: it a[10]; typedef it* ItPtr; ItPtr p; Variables a ad p are the same kid of variable Sice a is a poiter variable that poits to a[0], p = a; causes p to poit to the same locatio as a Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-29

Poiter Variables As Array Variables Cotiuig the previous example: Poiter variable p ca be used as if it were a array variable Display 9.4 Display 9.5 Example: p[0], p[1], p[9] are all legal ways to use p Variable a ca be used as a poiter variable except the poiter value i a caot be chaged This is ot legal: ItPtr p2; // p2 is assiged a value a = p2 // attempt to chage a Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-30

Creatig Dyamic Arrays Normal arrays require that the programmer determie the size of the array whe the program is writte What if the programmer estimates too large? Memory is wasted What if the programmer estimates too small? The program may ot work i some situatios Dyamic arrays ca be created with just the right size while the program is ruig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-31

Creatig Dyamic Arrays Dyamic arrays are created usig the ew operator Example: To create a array of 10 elemets of type double: typedef double* DoublePtr; DoublePtr d; d = ew double[10]; This could be a iteger variable! d ca ow be used as if it were a ordiary array! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-32

Dyamic Arrays (cot.) Poiter variable d is a poiter to d[0] Whe fiished with the array, it should be deleted to retur memory to the freestore Example: delete [ ] d; The brackets tell C++ a dyamic array is beig deleted so it must check the size to kow how may idexed variables to remove Forgettig the brackets, is ot legal, but would tell the computer to remove oly oe variable Display 9.6 (1) Display 9.6 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-33

Poiter Arithmetic (Optioal) Arithmetic ca be performed o the addresses cotaied i poiters Usig the dyamic array of doubles, d, declared previously, recall that d poits to d[0] The expressio d+1 evaluates to the address of d[1] ad d+2 evaluates to the address of d[2] Notice that addig oe adds eough bytes for oe variable of the type stored i the array Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-34

Poiter Arthmetic Operatios You ca add ad subtract with poiters The ++ ad - - operators ca be used Two poiters of the same type ca be subtracted to obtai the umber of idexed variables betwee The poiters should be i the same array! This code shows oe way to use poiter arithmetic: for (it i = 0; i < array_size; i++) cout << *(d + i) << " " ; // same as cout << d[i] << " " ; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-35

Multidimesioal Dyamic Arrays To create a 3x4 multidimesioal dyamic array View multidimesioal arrays as arrays of arrays First create a oe-dimesioal dyamic array Start with a ew defiitio: typedef it* ItArrayPtr; Now create a dyamic array of poiters amed m: ItArrayPtr *m = ew ItArrayPtr[3]; For each poiter i m, create a dyamic array of it's for (it i = 0; i<3; i++) m[i] = ew it[4]; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-36

A Multidimesial Dyamic Array m The dyamic array created o the previous slide could be visualized like this: ItArrayPtr's ItArrayPtr * it's Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-37

Deletig Multidimesioal Arrays To delete a multidimesioal dyamic array Each call to ew that created a array must have a correspodig call to delete[ ] Example: To delete the dyamic array created o a previous slide: for ( i = 0; i < 3; i++) delete [ ] m[i]; //delete the arrays of 4 it's delete [ ] m; // delete the array of ItArrayPtr's Display 9.7 (1) Display 9.7 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-38

Sectio 9.2 Coclusio Ca you Write a defiitio for poiter variables that will be used to poit to dyamic arrays? The array elemets are of type char. Call the type CharArray. Write code to fill array "etry" with 10 umbers typed at the keyboard? it * etry; etry = ew it[10]; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-39

Chapter 9 -- Ed Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-40

Display 9.1 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-41

Display 9.2 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-42

Display 9.3 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-43

Display 9.4 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-44

Display 9.5 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-45

Display 9.6 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-46

Display 9.6 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-47

Display 9.7 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-48

Display 9.7 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-49