Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Similar documents
Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Chapter 9. Pointers and Dynamic Arrays

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

Pointers and Dynamic Arrays

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

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

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

CSC 270 Survey of Programming Languages. What is a Pointer?

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Software Design and Analysis for Engineers

Pointers, Dynamic Data, and Reference Types

Launchpad Lecture -10

Object Oriented Software Design II

Homework #3 CS2255 Fall 2012

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

QUIZ. What is wrong with this code that uses default arguments?

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

A pointer variable has a pointer type, and holds pointer values. If a variable uses a number of adjacent locations, the address of the

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Vector and Free Store (Vectors and Arrays)

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CSC1322 Object-Oriented Programming Concepts


Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

CPSC 427: Object-Oriented Programming

Chapter 13: Copy Control. Overview. Overview. Overview

Intermediate Programming & Design (C++) Classes in C++

And Even More and More C++ Fundamentals of Computer Science

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

C++ 8. Constructors and Destructors

Constants, References

Absolute C++ Walter Savitch

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Short Notes of CS201

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

CS201- Introduction to Programming Current Quizzes

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Dynamic Memory Allocation

CS201 - Introduction to Programming Glossary By

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

CA31-1K DIS. Pointers. TA: You Lu

Chapter 7 Constructors and Other Tools. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Special Member Functions

Lecture 9. Pointer, linked node, linked list TDDD86: DALP. Content. Contents Pointer and linked node. 1.1 Introduction. 1.

Pointers and References

Pointers and Dynamic Memory Allocation

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

CS 161 Exam II Winter 2018 FORM 1

Goals of this Lecture

Ch. 12: Operator Overloading

CPSC 427: Object-Oriented Programming

CS201 Some Important Definitions

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

CS2255 HOMEWORK #1 Fall 2012

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Programming in C/C Lecture 2

AIMS Embedded Systems Programming MT 2017

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Dynamic Data Structures

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Object-Oriented Programming for Scientific Computing

Chapter 1: Object-Oriented Programming Using C++

G52CPP C++ Programming Lecture 13

Programming, numerics and optimization

Object Reference and Memory Allocation. Questions:

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

Functions and Parameter Passing

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

In Java we have the keyword null, which is the value of an uninitialized reference type

Scope. Scope is such an important thing that we ll review what we know about scope now:

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CS 376b Computer Vision

Object-Oriented Principles and Practice / C++

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

内存管理. Memory management

Interview Questions of C++

CPSC 427a: Object-Oriented Programming

Chapter 7. Constructors and Other Tools. Copyright 2016 Pearson, Inc. All rights reserved.

Written by John Bell for CS 342, Spring 2018

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Problem Solving with C++

Exam 3 Chapters 7 & 9

Pointers. Developed By Ms. K.M.Sanghavi

Software Design and Analysis for Engineers

Introducing C++ to Java Programmers

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Transcription:

Chapter 10 Pointers and Dynamic Arrays 1

Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this pointer Destructors, copy constructors 2

Pointer Introduction Pointer definition: Memory address of a variable Recall: memory divided Numbered memory locations Addresses used as name for variable You ve used pointers already! Call-by-reference parameters Address of actual argument was passed 3

Pointer Variables Pointers are "typed" Can store pointer in variable Not int, double, etc. Instead: A POINTER to int, double, etc.! Example: double *p; p is declared a "pointer to double" variable Can hold pointers to variables of type double Not other types! (unless typecast, but could be dangerous) 4

Declaring Pointer Variables Pointers declared like other types Add "*" before variable name Produces "pointer to" that type "*" must be before each variable int *p1, *p2, v1, v2; p1, p2 hold pointers to int variables v1, v2 are ordinary int variables 5

Addresses and Numbers Pointer is an address Address is an integer Pointer is NOT an integer! Not crazy à abstraction! C++ forces pointers be used as addresses Cannot be used as numbers Even though it "is a" number 6

Pointing Terminology, view Talk of "pointing", not "addresses" Pointer variable "points to" ordinary variable Leave "address" talk out Makes visualization clearer "See" memory references Arrows 7

Pointing to int *p1, *p2, v1, v2; p1 = &v1; Sets pointer variable p1 to "point to" int variable v1 Operator, & Determines "address of" variable Read like: "p1 equals address of v1" Or "p1 points to v1" 8

Pointing to Recall: int *p1, *p2, v1, v2; p1 = &v1; Two ways to refer to v1 now: Variable v1 itself: cout << v1; Via pointer p1: cout *p1; Dereference operator, * Pointer variable "derereferenced" Means: "Get data that p1 points to" 9

"Pointing to" Example Consider: v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; Produces output: 42 42 p1 and v1 refer to same variable 10

& Operator The "address of" operator Also used to specify call-by-reference parameter No coincidence! Recall: call-by-reference parameters pass "address of" the actual argument Operator s two uses are closely related 11

Pointer Assignments Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point to where p1 points" Do not confuse with: *p1 = *p2; Assigns "value pointed to" by p1, to "value pointed to" by p2 12

Pointer Assignments Graphic: Uses of the Assignment Operator with Pointer Variables 13

The new Operator Since pointers can refer to variables No "real" need to have a standard identifier Can dynamically allocate variables Operator new creates variables No identifiers to refer to them Just a pointer! p1 = new int; Creates new "nameless" variable, and assigns p1 to "point to" it Can access with *p1 Use just like ordinary variable 14

Basic Pointer Manipulations Basic Pointer Manipulations (1 of 2) 15

Basic Pointer Manipulations Basic Pointer Manipulations (2 of 2) 16

Basic Pointer Manipulations Explanation 17

More on new Operator Creates new dynamic variable Returns pointer to the new variable If type is class type: Constructor is called for new object Can invoke different constructor with initializer arguments: MyClass *mcptr; mcptr = new MyClass(32.0, 17); Can still initialize non-class types: int *n; n = new int(17); //Initializes *n to 17 18

Pointers and Functions Pointers are full-fledged types Can be used just like other types Can be function parameters Can be returned from functions Example: int* findotherpointer(int* p); This function declaration: Has "pointer to an int" parameter Returns "pointer to an int" variable 19

Memory Management Heap Also called "freestore" Reserved for dynamically-allocated variables All new dynamic variables consume memory in freestore If too many à could use all freestore memory Future "new" operations will fail if freestore is "full" 20

Checking new Success Older compilers: Test if null returned by call to new: int *p; p = new int; if (p == NULL) // NULL represents empty pointer { cout << "Error: Insufficient memory.\n"; exit(1); } If new succeeded, program continues 21

new Success New Compiler Newer compilers: If new operation fails: Program terminates automatically Produces error message Still good practice to use NULL check NULL represents the empty pointer or a pointer to nothing and will be used later to mark the end of a list 22

Freestore Size Varies with implementations Typically large Most programs won t use all memory Memory management Still good practice Solid software engineering principle Memory IS finite Regardless of how much there is! 23

delete Operator De-allocate dynamic memory When no longer needed Returns memory to freestore Example: int *p; p = new int(5); //Some processing delete p; De-allocates dynamic memory "pointed to by pointer p" Literally "destroys" memory 24

Dangling Pointers delete p; Destroys dynamic memory But p still points there! Called "dangling pointer" If p is then dereferenced ( *p ) Unpredicatable results! Often disastrous! Avoid dangling pointers Assign pointer to NULL after delete: delete p; p = NULL; 25

Dynamic and Automatic Variables Dynamic variables Created with new operator Created and destroyed while program runs Local variables Declared within function definition Not dynamic Created when function is called Destroyed when function call completes Often called "automatic" variables Properties controlled for you 26

Define Pointer Types Can "name" pointer types To be able to declare pointers like other variables Eliminate need for "*" in pointer declaration typedef int* IntPtr; Defines a "new type" alias Consider these declarations: IntPtr p; int *p; The two are equivalent 27

Pitfall: Call-by-value Pointers Behavior subtle and troublesome If function changes pointer parameter itself à only change is to local copy Best illustrated with example 28

A Call-by-Value Pointer Parameter (1 of 2) 29

A Call-by-Value Pointer Parameter (2 of 2) 30

The Function Call sneaky(p); 31

Dynamic Arrays Array variables Really pointer variables! Standard array Fixed size Dynamic array Size not specified at programming time Determined while program running 32

Array Variables Recall: arrays stored in memory addresses, sequentially Array variable "refers to" first indexed variable So array variable is a kind of pointer variable! Example: int a[10]; int * p; a and p are both pointer variables! 33

Array Variables à Pointers Recall previous example: int a[10]; typedef int* IntPtr; IntPtr p; a and p are pointer variables Can perform assignments: p = a; // Legal. p now points where a points a = p;» To first indexed variable of array a // ILLEGAL! Array pointer is CONSTANT pointer! 34

Array Variables à Pointers Array variable int a[10]; MORE than a pointer variable "const int *" type Array was allocated in memory already Variable a MUST point there always! Cannot be changed! In contrast to ordinary pointers Which can (& typically do) change 35

Dynamic Arrays Array limitations Must specify size first May not know until program runs! Must "estimate" maximum size needed Sometimes OK, sometimes not "Wastes" memory Dynamic arrays Can grow and shrink as needed 36

Creating Dynamic Arrays Very simple! Use new operator Dynamically allocate with pointer variable Treat like standard arrays Example: typedef double * DoublePtr; DoublePtr d; d = new double[10]; //Size in brackets Creates dynamically allocated array variable d, with ten elements, base type double 37

Deleting Dynamic Arrays Allocated dynamically at run-time So should be destroyed at run-time Simple again. Recall Example: d = new double[10]; //Processing delete [] d; De-allocates all memory for dynamic array Brackets indicate "array" is there Recall: d still points there! Should set d = NULL; 38

Function that Returns an Array Array type NOT allowed as return-type of function Example: int [] somefunction(); // ILLEGAL! Instead return pointer to array base type: int* somefunction(); // LEGAL! 39

Pointer Arithmetic Can perform arithmetic on pointers "Address" arithmetic Example: typedef double* DoublePtr; DoublePtr d; d = new double[10]; d contains address of d[0] d + 1 evaluates to address of d[1] d + 2 evaluates to address of d[2] Equates to "address" at these locations 40

Alternative Array Manipulation Use pointer arithmetic! "Step thru" array without indexing: for (int i = 0; i < arraysize; i++) cout << *(d + I) << " " ; Equivalent to: for (int i = 0; i < arraysize; i++) cout << d[i] << " " ; Only addition/subtraction on pointers No multiplication, division Can use ++ and -- on pointers 41

Multidimensional Dynamic Arrays Yes we can! Recall: "arrays of arrays" Type definitions help "see it": typedef int* IntArrayPtr; IntArrayPtr *m = new IntArrayPtr[3]; Creates array of three pointers Make each allocate array of 4 ints for (int i = 0; i < 3; i++) m[i] = new int[4]; Results in three-by-four dynamic array! 42

Back to Classes The -> operator Shorthand notation Combines dereference operator, *, and dot operator Specifies member of class "pointed to" by given pointer Example: MyClass *p; p = new MyClass; p->grade = "A"; (*p).grade = "A"; Equivalent to: 43

The this Pointer Member function definitions might need to refer to calling object Use predefined this pointer Automatically points to calling object: Class Simple { public: void showstuff() const; private: int stuff; }; Two ways for member functions to access: cout << stuff; cout << this->stuff; 44

Overloading Assignment Operator Assignment operator returns reference So assignment "chains" are possible e.g., a = b = c; Sets a and b equal to c Operator must return "same type" as it s left-hand side To allow chains to work The this pointer will help with this! 45

Overloading Assignment Operator Recall: Assignment operator must be member of the class It has one parameter Left-operand is calling object s1 = s2; Think of like: s1.=(s2); s1 = s2 = s3; Requires (s1 = s2) = s3; So (s1 = s2) must return object of s1 s type And pass to " = s3"; 46

Overloaded = Operator Definition Uses string Class example: StringClass& StringClass::operator=(const StringClass& rtside) { if (this == &rtside) return *this; else { capacity = rtside.length; length = rtside.length; delete [] a; a = new char[capacity]; for (int I = 0; I < length; I++) a[i] = rtside.a[i]; return *this; } } 47

Shallow and Deep Copies Shallow copy Assignment copies only member variable contents over Default assignment and copy constructors Deep copy Pointers, dynamic memory involved Must dereference pointer variables to "get to" data for copying Write your own assignment overload and copy constructor in this case! 48

Destructor Need Dynamically-allocated variables Do not go away until "deleted" If pointers are only private member data They dynamically allocate "real" data In constructor Must have means to "deallocate" when object is destroyed Answer: destructor! 49

Destructors Opposite of constructor Automatically called when object is out-of-scope Default version only removes ordinary variables, not dynamic variables Defined like constructor, just add ~ MyClass::~MyClass() { //Perform delete clean-up duties } 50

Copy Constructors Automatically called when: Class object declared and initialized to other object When function returns class type object When argument of class type is "plugged in" as actual argument to call-by-value parameter Requires "temporary copy" of object Copy constructor creates it Default copy constructor Like default "=", performs member-wise copy Pointers à write own copy constructor! 51