Concordia University Department of Computer Science and Software
- Slides: 109
Concordia University Department of Computer Science and Software Engineering COMP 345 Advanced program design with C++ Slide set 3: static and dynamic arrays Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -1
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 -2
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 -3
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 -4
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 -5
Array Usage ¨ Powerful storage mechanism ¨ Can issue command like: ¨ "Do this to ith 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 -6
Program Using an Array (1 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -7
Program Using an Array (2 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -8
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 -9
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 -10
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 -11
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 -12
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: last. Index = (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 -13
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 -14
An Array in Memory Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -15
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, 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 -16
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 -17
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 -18
Indexed Variables as Arguments ¨ Indexed variable handled same as simple variable of array base type ¨ Given this function declaration: void my. Function(double par 1); ¨ And these declarations: int i; double n, a[10]; ¨ Can make these function calls: my. Function(i); // i is converted to double my. Function(a[3]); // a[3] is double my. Function(n); // n is double Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -19
Subtlety of Indexing ¨ Consider: my. Function(a[i]); ¨ Value of i is determined first ¨ It determines which indexed variable is sent my. Function(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 -20
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 -21
Entire Array as Argument Example Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -22
Entire Array as Argument Example ¨ Given previous example: ¨ In some main() function definition, consider this call: int score[5], number. Of. Scores = 5; fillup(score, number. Of. Scores); ¨ 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 -23
Array as Argument: How? ¨ What’s really passed? ¨ Think of array as 3 "pieces" ¨ Address of first indexed variable (arr. Name[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 -24
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]; fill. Up(score, 5); fill. Up(time, 10); Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -25
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 -26
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 -27
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 -28
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 number. Used; ¨ Tracks current number of elements in array Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -29
Partially-filled Arrays Example: Partially Filled Array (1 of 5) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -30
Partially-filled Arrays Example: Partially Filled Array (2 of 5) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -31
Partially-filled Arrays Example: Partially Filled Array (3 of 5) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -32
Partially-filled Arrays Example: Partially Filled Array (4 of 5) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -33
Partially-filled Arrays Example: Partially Filled Array (5 of 5) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -34
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 -35
Searching an Array (1 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -36
Searching an Array (2 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -37
Searching an Array (3 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -38
Searching an Array (4 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -39
Sorting an Array: Selection Sort ¨ Selection Sort Algorithm Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -40
Sorting an Array (1 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -41
Sorting an Array (2 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -42
Sorting an Array (3 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -43
Sorting an Array (4 of 4) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -44
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 -45
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 display. Page(const char p[][100], int size. Dimension 1) { for (int index 1=0; index 1<size. Dimension 1; index 1++) { for (int index 2=0; index 2 < 100; index 2++) cout << p[index 1][index 2]; cout << endl; } } Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -46
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 -47
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 -48
Dynamic arrays and pointers Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -49
Learning Objectives ¨ 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 -50
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 -51
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 -52
Declaring Pointer Variables ¨ Pointers declared like other types ¨ Add "*" before variable name ¨ Produces "pointer to" that type ¨ "*" must be before each variable declaration ¨ int *p 1, *p 2, v 1, v 2; ¨ p 1, p 2 hold pointers to int variables ¨ v 1, v 2 are ordinary int variables Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -53
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 -54
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 -55
Pointing to … int *p 1, *p 2, v 1, v 2; p 1 = &v 1; ¨ Sets pointer variable p 1 to "point to" int variable v 1 ¨ Operator, & ¨ Determines "address of" variable ¨ Read like: ¨ "p 1 equals address of v 1" ¨ Or "p 1 points to v 1" Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -56
Pointing to … ¨ Recall: int *p 1, *p 2, v 1, v 2; p 1 = &v 1; ¨ Two ways to refer to v 1 now: ¨ Variable v 1 itself: cout << v 1; ¨ Via pointer p 1: cout << *p 1; ¨ Dereference operator, * ¨ Pointer variable "derereferenced" ¨ Means: "Get data that p 1 points to" Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -57
"Pointing to" Example ¨ Consider: v 1 = 0; p 1 = &v 1; *p 1 = 42; cout << v 1 << endl; cout << *p 1 << endl; ¨ Produces output: 42 42 ¨ p 1 and v 1 refer to same memory cell Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -58
& 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 -59
Pointer Assignments ¨ Pointer variables can be "assigned": int *p 1, *p 2; p 2 = p 1; ¨ Assigns one pointer to another ¨ "Make p 2 point to where p 1 points“ ¨ Do not confuse with: *p 2 = *p 1; ¨ Assigns "value pointed to" by p 1, to "value pointed to" by p 2 Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -60
Pointer Assignments Graphic: Uses of the Assignment Operator with Pointer Variables Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -61
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! ¨ p 1 = new int; ¨ Creates new "nameless" variable, and assigns p 1 to "point to" it ¨ Can access its value with *p 1 ¨ Use just like ordinary variable Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -62
Basic Pointer Manipulations (1 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -63
Basic Pointer Manipulations (2 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -64
Basic Pointer Manipulations Graphic: Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -65
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: My. Class *mc. Ptr; mc. Ptr = new My. Class(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 -66
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* find. Other. Pointer(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 -67
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 -68
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 -69
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 -70
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 -71
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 -72
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 -73
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 -74
Define Pointer Types ¨ Can "name" pointer types ¨ To be able to declare pointers like other variables ¨ Eliminate need for "*" in pointer declaration ¨ typedef int* Int. Ptr; ¨ Defines a "new type" alias ¨ Consider these declarations: Int. Ptr p; int *p; ¨ The two are equivalent Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -75
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 -76
A Call-by-Value Pointer Parameter (1 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -77
A Call-by-Value Pointer Parameter (2 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -78
Call-by-value Pointers Graphic: The Function Call sneaky(p); Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -79
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 -80
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 -81
Array Variables Pointers ¨ Recall previous example: int a[10]; typedef int* Int. Ptr; Int. Ptr 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 -82
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 -83
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 -84
Creating Dynamic Arrays ¨ Very simple! ¨ Use new operator ¨ Dynamically allocate with pointer variable ¨ Treat like standard arrays ¨ Example: typedef double * Double. Ptr; Double. Ptr 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 -85
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 -86
Function that Returns an Array ¨ Array type NOT allowed as return-type of function ¨ Example: int [] some. Function(); // ILLEGAL! ¨ Instead return pointer to array base type: int* some. Function(); // LEGAL! Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -87
Pointer Arithmetic ¨ Can perform arithmetic on pointers ¨ "Address" arithmetic ¨ Example: typedef double* Double. Ptr; Double. Ptr 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 -88
Alternative Array Manipulation ¨ Use pointer arithmetic! ¨ "Step thru" array without indexing: for (int i = 0; i < array. Size; i++) cout << *(d + I) << " " ; ¨ Equivalent to: for (int i = 0; i < array. Size; 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 -89
Multidimensional Dynamic Arrays ¨ Yes we can! ¨ Recall: "arrays of arrays" ¨ Type definitions help "see it": typedef int* Int. Array. Ptr; Int. Array. Ptr *m = new Int. Array. Ptr[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 -90
Back to Classes ¨ The -> operator ¨ Shorthand notation ¨ Combines dereference operator, *, and dot operator ¨ Specifies member of class "pointed to" by given pointer ¨ Example: My. Class *p; p = new My. Class; p->grade = "A"; //Equivalent to: (*p). grade = "A"; Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -91
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 show. Stuff() const; private: int stuff; }; ¨ Two ways for member functions to access: cout << stuff; cout << this->stuff; Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -92
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 -93
Overloading Assignment Operator ¨ Recall: Assignment operator must be member of the class ¨ It has one parameter ¨ Left-operand is calling object s 1 = s 2; ¨ Think of like: s 1. =(s 2); ¨ s 1 = s 2 = s 3; ¨ Requires (s 1 = s 2) = s 3; ¨ So (s 1 = s 2) must return object of s 1’s type ¨ And pass to " = s 3"; Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -94
Overloaded = Operator Definition ¨ Uses string Class example: String. Class& String. Class: : operator=(const String. Class& rt. Side) { if (this == &rt. Side)// if right side same as left side return *this; else { capacity = rt. Side. length; length = rt. Side. 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] = rt. Side. a[I]; return *this; } } Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -95
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 -96
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 -97
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 ~ ¨ My. Class: : ~My. Class() { //Perform delete clean-up duties } Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -98
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 ¨ ¨ Default copy constructor ¨ ¨ Copy constructor creates it Like default "=", performs member-wise copy Pointers write own copy constructor! Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -99
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 3 -100
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 3 -101
Vectors Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -102
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 3 -103
Vector Basics ¨ Similar to array: ¨ Has base type ¨ Stores collection of base type values ¨ Declared differently: ¨ Syntax: vector<Base_Type> ¨ Indicates template class ¨ Any type can be "plugged in" to Base_Type ¨ Produces "new" class for vectors with that type ¨ Example declaration: vector<int> v; Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -104
Vector Use ¨ vector<int> 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 3 -105
Vector Example: Using a Vector (1 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -106
Vector Example: Using a Vector (2 of 2) Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -107
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 3 -108
Summary 1 ¨ Vector classes ¨ Like: "arrays that grow and shrink" Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3 -109
- Columbia university department of computer science
- Concordia university mechanical engineering
- Software engineering concordia
- Software engineering concordia
- Software engineering concordia
- Ucl university computer science
- Northwestern computer science department
- Computer science department rutgers
- Stanford vptl tutoring
- Fsu cybersecurity major
- Ubc computer science department
- Department of computer science christ
- Eric’s favourite .......... is science
- Phoenix online computer science university
- Bridgeport engineering department
- University of bridgeport computer engineering
- Computer science yonsei university
- York university computer science
- Computer science unc chapel hill
- Seoul national university computer science
- Osaka university computer science
- Computer science columbia university
- 7800 york road
- Kansas state university computer science
- Brown university computer science
- Trinity university computer science
- Brandeis university computer science
- Institute of computer science university of tartu
- Kotebe metropolitan university
- Software engineer vs software developer
- Computer science software engineering
- Computer science software engineering
- Hvg concordia
- Mystudentcenter concordia
- Soen 6441 concordia
- Cameron skinner
- Concordia international school hong kong
- Aiman hanna concordia
- Titanic vs costa concordia
- Diocesi concordia pordenone ufficio catechistico
- Coen 311 concordia
- Comp 6321
- Concordia r2
- Banweb concordia
- Graziano diritto canonico
- Hay quienes pretenden ser ricos
- Gradproskills
- Originality form concordia
- Iit delhi material science faculty
- Tum department of electrical and computer engineering
- Department of law university of jammu
- Department of geology university of dhaka
- University of padova psychology
- University of bridgeport it department
- University of iowa math department
- Department of physics university of tokyo
- Texas state university psychology
- Department of information engineering university of padova
- Information engineering padova
- Manipal university chemistry department
- Syracuse university pool
- Jackson state university finance department
- Michigan state university astronomy
- Columbia university cs department
- University of sargodha engineering department
- Stanford university philosophy department
- Department of forensic science dc
- Oh.nesinc
- Computer engineering department
- University of science and technology of hanoi
- Ulsan national institute of science and technology (unist)
- Science technology university yemen
- Jordan university of science and technology
- Jordan university of science and technology ranking
- Jordan university of science and technology
- University of shanghai for science and technology
- University of science and technology of mazandaran
- Pingtung university of science and technology
- University of science and technology kumasi
- East china university of political science and law
- Mongolian university of science and technology logo
- National yunlin university of science and technology
- Rapid change
- Sciencefusion think central
- Hard and soft science
- Computer science input and output
- Difference between ba and bs in computer science
- Ucf computer engineering
- Erik jonsson school of engineering and computer science
- Computer science and engineering unr
- Ucla
- Https.//makecode.microbit.org
- Erik jonsson school of engineering and computer science
- Erik jonsson school of engineering and computer science
- Objectives of computer
- What is computer organization
- Computer, computer basics, input and output devices
- Computer architecture vs computer organization
- Computer graphics hardware and software
- Introduction to software and hardware
- A computer system consists of both hardware and software
- 詹景裕
- Skills and applications chapter 3
- Difference between generic software and custom software
- Difference between student software and industrial software
- What is software measurement
- Institute of industrial science the university of tokyo
- Data science lab ryerson
- Esslingen university of applied science
- Warsaw university political science