Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 10 Pointers and Dynamic Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Pointers Pointer variables.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 8 Arrays and Strings
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
C/C++ Basics (IV) Array, Pointers and Dynamic Arrays Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Slide 1 Chapter 10 Pointers and Dynamic Arrays. Slide 2 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating.
Pointers and Dynamic Arrays
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Chapter 10 Pointers and Dynamic Arrays. Learning Objectives Pointers – Pointer variables – Memory management Dynamic Arrays – Creating and using – Pointer.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Chapter 12 Pointers and Dynamic Arrays. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Pointers (12.1) Dynamic Arrays.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Pointers  * symbol and & symbol  Pointer operations  Pointer.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers CSC1201: Programming Language 2. Topics Pointers ▫Memory addresses ▫Declaration ▫Dereferencing a pointer ▫Pointers to pointer.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Pointers and Dynamic Arrays
COMP 2710 Software Construction Pointers
Advanced Program Design with C++
7 Arrays.
Constructors and Other Tools
Review of Everything Arrays
CMSC202 Computer Science II for Majors Lecture 03 – Arrays and Functions Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
7 Arrays.
9-10 Classes: A Deeper Look.
9-10 Classes: A Deeper Look.
Presentation transcript:

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced program design with C++ Slide set 3: static and dynamic arrays

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory  Arrays in Functions  Arrays as function arguments, return values  Programming with Arrays  Partially Filled Arrays, searching, sorting  Multidimensional Arrays

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-3 Introduction to Arrays  Array definition:  A collection of data of same type  First "aggregate" data type  Means "grouping"  int, float, double, char are simple data types  Used for lists of like items  Test scores, temperatures, names, etc.  Avoids declaring multiple simple variables  Can be manipulated as a single entity, with some restrictions

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-4 Declaring Arrays  Declare the array : allocates memory int score[5];  Declares array of 5 integers named " score "  Similar to declaring five variables: int score[0], score[1], score[2], score[3], score[4]  Individual parts called many things:  Indexed or subscripted variables  “Elements” of the array  Value in brackets called index or subscript  Numbered from [0] to [size – 1]

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-5 Accessing Arrays  Access using index/subscript cout << score[3];  Note two uses of brackets:  In declaration, specifies SIZE of array  Anywhere else, specifies a SUBSCRIPT  Size and subscript need not be literal int score[MAX_SCORES]; score[n+1] = 99;  If n is 2, identical to: score[3]  However, the SIZE needs to be a CONSTANT  Subscript can be any expression eventually evaluating to an integer value (constant or not)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-6 Array Usage  Powerful storage mechanism  Can issue command like:  "Do this to i th indexed variable" where i is computed by program  "Display all elements of array score"  "Fill elements of array score from user input"  "Find highest value in array score"  "Find lowest value in array score"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-7 Program Using an Array (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-8 Program Using an Array (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-9 for-loops with Arrays  Natural counting loop  Naturally works well "counting thru" elements of an array  Example: for (idx = 0; idx<5; idx++) { cout << score[idx] << "off by " << max – score[idx] << endl; }  Loop control variable ( idx ) counts from 0 to 5

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-10 Major Array Pitfall  Array indexes always start with zero!  Zero is "first" number to computer scientists  C++ will "let" you go beyond range  Unpredictable results  Compiler will not detect these errors!  Up to programmer to "stay in range"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-11 Major Array Pitfall Example  Indexes range from 0 to (array_size – 1)  Example: double temperature[24]; // 24 is array size // Declares array of 24 double values // called temperature  They are indexed as: temperature[0], temperature[1] … temperature[23]  Common mistake: temperature[24] = 5;  Index 24 is "out of range"!  No warning, possibly disastrous results

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-12 Defined Constant as Array Size  Always use defined/named constant for array size  Example: const int NUMBER_OF_STUDENTS = 5; int score[NUMBER_OF_STUDENTS];  Improves readability  Improves versatility  Improves maintainability

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-13 Uses of Defined Constant  Use everywhere size of array is needed  In for-loop for traversal: for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++) { // Manipulate array }  In calculations involving size: lastIndex = (NUMBER_OF_STUDENTS – 1);  When passing array to functions (later)  If size changes  requires only ONE change in program (and recompilation)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-14 Arrays in Memory  Recall simple variables:  Allocated memory in an "address"  Array declarations allocate memory for entire array  Sequentially-allocated  Means addresses allocated "back-to-back"  Allows indexing calculations  Simple "addition" from array beginning (index 0)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-15 An Array in Memory

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-16 Initializing Arrays  As simple variables can be initialized at declaration: int price = 0;// 0 is initial value  Arrays can as well: int children[3] = {2, 12, 1};  Equivalent to following: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1;

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-17 Auto-Initializing Arrays  If fewer values than size supplied:  Fills from beginning  Fills "rest" with zero of array base type  If array-size is left out  Declares array with size required based on number of initialization values  Example: int b[] = {5, 12, 11};  Allocates array b to size 3

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-18 Arrays in Functions  As arguments to functions  Indexed variables  An individual "element" of an array can be function parameter  Entire arrays  All array elements can be passed as "one entity“  As return value from function  Can be done

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-19 Indexed Variables as Arguments  Indexed variable handled same as simple variable of array base type  Given this function declaration: void myFunction(double par1);  And these declarations: int i; double n, a[10];  Can make these function calls: myFunction(i); // i is converted to double myFunction(a[3]); // a[3] is double myFunction(n); // n is double

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-20 Subtlety of Indexing  Consider: myFunction(a[i]);  Value of i is determined first  It determines which indexed variable is sent myFunction(a[i*5]);  Perfectly legal, from compiler’s view  Programmer responsible for staying "in-bounds" of array

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-21 Entire Arrays as Arguments  Formal parameter can be entire array  Argument then passed in function call is array name  Called "array parameter“  Send size of array as well  Typically done as second parameter  Simple int type formal parameter

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-22 Entire Array as Argument Example

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-23 Entire Array as Argument Example  Given previous example:  In some main() function definition, consider this call: int score[5], numberOfScores = 5; fillup(score, numberOfScores);  1 st argument is entire array  2 nd argument is integer value  Note no brackets in array argument!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-24 Array as Argument: How?  What’s really passed?  Think of array as 3 "pieces"  Address of first indexed variable ( arrName[0] )  Array base type  Size of array  Only 1 st piece is passed!  Just the beginning address of array  Very similar to "pass-by-reference"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-25 Array Parameters  May seem strange  No brackets in array argument  Must send size separately  One nice property:  Can use SAME function to fill any size array!  Exemplifies "re-use" properties of functions  Example: int score[5], time[10]; fillUp(score, 5); fillUp(time, 10);

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-26 The const Parameter Modifier  Recall: array parameter actually passes address of 1 st element  Similar to pass-by-reference  Function can then modify array!  Often desirable, sometimes not!  Protect array contents from modification  Use " const " modifier before array parameter  Called "constant array parameter"  Tells compiler to "not allow" modifications

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-27 Functions that Return an Array  Functions cannot return arrays in the same way simple types are returned  Requires use of a pointer

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-28 Programming with Arrays  Plenty of uses  Partially-filled arrays  Must be declared some "max size"  Sorting  Searching

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-29 Partially-filled Arrays  Difficult to know exact array size needed  Must declare to be largest possible size  Must then keep "track" of valid data in array  Additional "tracking" variable needed  int numberUsed;  Tracks current number of elements in array

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-30 Partially-filled Arrays Example: Partially Filled Array (1 of 5)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-31 Partially-filled Arrays Example: Partially Filled Array (2 of 5)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-32 Partially-filled Arrays Example: Partially Filled Array (3 of 5)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-33 Partially-filled Arrays Example: Partially Filled Array (4 of 5)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-34 Partially-filled Arrays Example: Partially Filled Array (5 of 5)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-35 Global Constants vs. Parameters  Constants typically made "global"  Declared above main()  Functions then have scope to array size constant  No need to send as parameter then?  Technically yes  Why should we anyway?  Function definition might be in separate file  Function might be used by other programs!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-36 Searching an Array (1 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-37 Searching an Array (2 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-38 Searching an Array (3 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-39 Searching an Array (4 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-40 Sorting an Array: Selection Sort  Selection Sort Algorithm

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-41 Sorting an Array (1 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-42 Sorting an Array (2 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-43 Sorting an Array (3 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-44 Sorting an Array (4 of 4)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-45 Multidimensional Arrays  Arrays with more than one index  char page[30][100];  Two indexes: An "array of arrays"  Visualize as: page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], …, page[29][99]  C++ allows any number of indexes  Typically no more than two

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-46 Multidimensional Array Parameters  Similar to one-dimensional array  1 st dimension size not given  Provided as second parameter  2 nd dimension size IS given  Example: void displayPage(const char p[][100], int sizeDimension1) { for (int index1=0; index1<sizeDimension1; index1++) { for (int index2=0; index2 < 100; index2++) cout << p[index1][index2]; cout << endl; } }

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-47 Summary 1  Array is collection of "same type" data  Indexed variables of array used just like any other simple variables  for-loop "natural" way to traverse arrays  Programmer responsible for staying "in bounds" of array  Array parameter is "new" kind  Similar to call-by-reference

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-48 Summary 2  Array elements stored sequentially  "Contiguous" portion of memory  Only address of 1 st element is passed to functions  Partially-filled arrays  more tracking  Constant array parameters  Prevent modification of array contents  Multidimensional arrays  Create "array of arrays"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-49 Dynamic arrays and pointers

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-50 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating and using  Pointer arithmetic  Classes, Pointers, Dynamic Arrays  The this pointer  Destructors, copy constructors

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-51 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-52 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-53 Declaring Pointer Variables  Pointers declared like other types  Add "*" before variable name  Produces "pointer to" that type  "*" must be before each variable declaration  int *p1, *p2, v1, v2;  p1, p2 hold pointers to int variables  v1, v2 are ordinary int variables

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-54 Addresses and Numbers  Pointer is an address  Address is an integer  Pointer is NOT an integer!  C++ forces pointers be used as addresses  Cannot be used as numbers  Even though it "is a" number

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-55 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-56 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 "

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-57 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"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-58 "Pointing to" Example  Consider: v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl;  Produces output:  p1 and v1 refer to same memory cell

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-59 & 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-60 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: *p2 = *p1;  Assigns "value pointed to" by p1, to "value pointed to" by p2

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-61 Pointer Assignments Graphic: Uses of the Assignment Operator with Pointer Variables

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-62 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 its value with *p1  Use just like ordinary variable

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-63 Basic Pointer Manipulations (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-64 Basic Pointer Manipulations (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-65 Basic Pointer Manipulations Graphic:

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-66 More on new Operator  Creates new dynamic variable  Allocated on the heap.  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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-67 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-68 Memory Management  Heap  Also called "freestore"  Reserved for dynamically-allocated variables  All new dynamic variables consume memory from the freestore  If too many  could use all freestore memory  Future new operations will fail if freestore is "full"

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-69 Checking new Success  Older compilers:  Test if null returned by call to new : int *p; p = new int; if (p == NULL) { cout << "Error: Insufficient memory.\n"; exit(1); }  If new succeeded, program continues

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-70 new Success – New Compiler  Newer compilers:  If new operation fails:  Program terminates automatically  Produces error message  Still good practice to use NULL check

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-71 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-72 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 content

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-73 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;

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-74 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-75 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-76 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…

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-77 A Call-by-Value Pointer Parameter (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-78 A Call-by-Value Pointer Parameter (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-79 Call-by-value Pointers Graphic: The Function Call sneaky(p);

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-80 Dynamic Arrays  Array variables  Really pointer variables!  Standard array  Fixed size  Dynamic array  Size not specified at programming time  Determined while program running

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-81 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-82 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  To first indexed variable of array a  a = p;// ILLEGAL!  Array pointer is CONSTANT pointer!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-83 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 (and typically do) change

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-84 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-85 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-86 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;

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-87 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-88 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-89 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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-90 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-91 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"; //Equivalent to: (*p).grade = "A";

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-92 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;

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-93 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-94 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 ";

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-95 Overloaded = Operator Definition  Uses string Class example: StringClass& StringClass::operator=(const StringClass& rtSide) { if (this == &rtSide)// if right side same as left side return *this; else { capacity = rtSide.length; length = rtSide.length; delete [] a; // a is a char array class member // that stores the string a = new char[capacity]; for (int I = 0; I < length; I++) a[I] = rtSide.a[I]; return *this; } }

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-96 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-97 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-98 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 }

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-99 Copy Constructors  Automatically called when: 1. Class object declared and initialized to other object 2. When function returns class type object 3. 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!

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Summary 1  Pointer is memory address  Provides indirect reference to variable  Dynamic variables  Created and destroyed while program runs  Freestore  Memory storage for dynamic variables  Dynamically allocated arrays  Size determined as program runs

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Summary 2  Class destructor  Special member function  Automatically destroys objects  Copy constructor  Single argument member function  Called automatically when temp copy needed  Assignment operator  Must be overloaded as member function  Returns reference for chaining

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vectors

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vectors  Vector Introduction  Recall: arrays are fixed size  Vectors: "arrays that grow and shrink"  During program execution  Formed from Standard Template Library (STL)  Using template class

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vector Basics  Similar to array:  Has base type  Stores collection of base type values  Declared differently:  Syntax: vector  Indicates template class  Any type can be "plugged in" to Base_Type  Produces "new" class for vectors with that type  Example declaration: vector v;

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vector Use  vector v;  "v is vector of type int"  Calls class default constructor  Empty vector object created  Indexed like arrays for access  But to add elements:  Must call member function push_back  Member function size()  Returns current number of elements

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vector Example: Using a Vector (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vector Example: Using a Vector (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Vector Efficiency  Member function capacity()  Returns memory currently allocated  Not same as size()  Capacity typically > size  Automatically increased as needed  If efficiency critical:  Can set behaviors manually v.reserve(32); //sets capacity to 32 v.reserve(v.size()+10); //sets capacity to 10 more than size

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet Summary 1  Vector classes  Like: "arrays that grow and shrink"