Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.

Slides:



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

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345.
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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 2:
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
ISBN Chapter 6 Data Types: Structured types.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
 2006 Pearson Education, Inc. All rights reserved Arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Pointers Applications
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
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
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
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.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
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.
Copyright © 2002 Pearson Education, Inc. Slide 1.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Windows Programming Lecture 03. Pointers and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Advanced Program Design with C++
7 Arrays.
7 Arrays.
Presentation transcript:

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays Dynamic arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Array definition: A collection of data elements of same type Identified by a sequential index Simple aggregate data type Can create arrays of elements of any type Used for lists of related items Test scores, temperatures, names, etc. Avoids declaring multiple simple variables Can be manipulated as a single entity, with some restrictions Arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Declaring an array allocates memory on the stack: 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 are often called using different terms: Indexed or subscripted variables Elements of the array Value in brackets called index or subscript Numbered from [0] to [size – 1] Declaring an array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Access using index/subscript cout << score[3]; Note two different uses of brackets: In declaration, specifies the size of the array Anywhere else, specifies an index 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 expression A constant expression is an expression that is composed of only constant components. Why? The compiler needs to know what is the size of the array in order to allocate memory to it at compile time. Subscript can be any expression eventually evaluating to an integer value (constant or not) Accessing an array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Simple program using an array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Simple program using an array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Arrays and loops Loop constructs naturally works well for "counting through" elements of an array Example: for (int idx = 0; idx<5; idx++) { cout << score[idx] << "off by " << max – score[idx] << endl; } Loop control variable idx counts from 0 to 4 Arrays and loops Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Valid range: Start with zero Zero is the first number in natural numbers Index is used to compute offset of value in the array End with size -1 C++ will let you go beyond range Unpredictable results Compiler will not detect these errors! In many cases, execution will continue as if nothing wrong happened Up to programmer to stay in range Major source of bugs A major feature in the toolbox of malicious programmers… Index range Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering 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 Use of constant as size Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering 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) If not, need to track required changes in many places, which is very error-prone. Use of constant as size Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Array are stored as a contiguous block of memory. Arrays are implicitly managed using pointers and pointer arithmetics. Given: int a[3]; int b; The elements of a are of type int. However, a itself is implicitly a pointer that points to the first element of a. Given an index, the compiler calculates an address offset that now points to the proper array element. It will not check whether this points outside of the array. Arrays in memory Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering As simple variables can be initialized at declaration: int price1 = 0; int price2 {0}; Arrays can be initialized as well: int children[3] = {2, 12, 1}; Equivalent to following: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; If the number of elements in the initialization list is greater than the size of the array, it generates a compile-time error. If the number of elements in the initialization list is lesser than the size of the array, all missing elements are initialized to 0. If the size is not specified, the size is assumed to be equal to the number of elements in the initialization list. Array initialization Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Arrays can be passed as parameters to functions. In order to compile and do processing on an array in functions receiving an array as parameter, three things are needed: Address of array: to generate offsets during compilation of the code to refer to the proper addresses where each array element resides. Array base type: for type checking during compilation. Size of array: To know how many elements there are in the array, e.g. to implement a loop over the entire array. Syntax allows to pass an array as a parameter: int myfunc(int p[]); However, what is really happening if you use that, is that only a pointer to p is passed as value. myfunc operates on the original array myfunc is not aware of the size of the array passed Passing arrays as parameters Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Functions cannot return arrays in the same way simple types are returned. Requires use of a pointer. The reason behind this is the same reason as for passing arrays as pointers: efficiency. Passing an array as value, or returning an array from a function, or having array assignment would assume that arrays are copied as they are passed around and manipulated, leading to increased memory consumption and execution time. C/C++ are designed for efficiency. Returning an array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: partially filled arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style example: searching in a partially-filled array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: searching in a partially-filled array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: searching in a partially-filled array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: searching in a partially-filled array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: searching in a partially-filled array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Example: selection sort Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering 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 Multidimensional arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering A one-dimensional array is stored as a pointer to an array of data elements. A two-dimensional array is stored as a pointer to an array of arrays of data elements. And so on and so forth… int a[3][4]; Multidimensional arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Similar to one-dimensional array 1 st dimension size not given Provided as second parameter 2 nd dimension, and succeeding size is given though Why? The compiler needs to know the sizes of the dimensions in order to calculate the offsets, as each row is of a fixed size specified by the number of elements in the array. This restriction greatly limits the usefulness of static multidimensional arrays as parameters. 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; } } Passing multidimensional arrays as a parameter Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering As the array is also stored in contiguous memory space, pointer arithmetic can still be used. However, each row needs to be entirely skipped if referring to an element of further rows. Multidimensional arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Multidimensional arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style dynamically allocated arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Static array limitations Must specify size first May not know until program runs. Very limited in its application. May use partially filled arrays for more flexibility Must estimate maximum size needed Wastes memory Dynamic arrays Can grow and shrink as needed Implemented as a pointer to a dynamically allocated static array. Dynamically allocated arrays Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Use new operator Create a pointer variable to the base type of the array elements. Dynamically allocate an array using new. Make the pointer variable point to the newly allocated array. Then treat just like a standard array. If size needs to be changed, just create a new one of different size, and copy the elements into the newly created one. Example: double *d; d = new double[10]; Creates dynamically allocated array variable d, with ten elements of base type double. Stored using the same model as a static array, except that the arrays of elements is stored on the heap instead of the stack, and thus each need to be pointed to by a pointer, thus it requires arrays of pointers. Initializing a dynamically allocated array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Allocated dynamically at run-time. So should be destroyed explicitly at run-time. double *d; d = new double[10]; … //Processing delete [] d; delete [] de-allocates all memory for a dynamic array Brackets indicate array is pointed to Recall: d still points there! Should set d = NULL; How does it know the size of what was pointed to? When you call new double[10], the run-time system actually stores the size of the array that it is allocating. It then uses this information when you call delete [] d Deallocating a dynamically allocated array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Can also be done by explicitly creating a nested array using pointers similar to a static array. For example, to create an 3x4 array of integers: First, create the array of 3 pointers that will eventually point to the 3 arrays of 4 integers, create a pointer variable that points to it (which is thus a pointer to a pointer to an int ): int** a = new int*[3]; Then use a loop to allocate 3 arrays of integers and have the pointers point to them: for (int i = 0; i < 3; i++) a[i] = new int[4]; Results in three-by-four dynamic array Same structure as an equivalent static array, except that it is allocated on the heap, and uses additional pointers. Multidimensional dynamically allocated array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Multidimensional dynamically allocated array Joey Paquet, COMP Advanced Program Design with C++ Results in three-by-four dynamic array Not same structure as an equivalent static array: Requires an additional pointer redirection level for each additional dimension. Allocated on the heap, which cannot be assumed to be allocated contiguously. Hence, the same simple pointer arithmetic does not apply.

Concordia University Department of Computer Science and Software Engineering As it was dynamically allocated, it then needs to be explicitly deallocated. Each sub-array element has to be explicitly deallocated: First, delete the arrays of integers: for (int i = 0; i < 3; i++) delete [] a[i]; Then delete the array of pointers: delete [] a; One more embedded for loop for each additional dimension. Tedious and careful memory management is required. Multidimensional dynamically allocated array Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering The Boost library also has an array class that implements a simple class embedding a static array and that stores its own size, making it much more practical than C++ basic static arrays. Some say that one should always use STL containers such as vector instead of dynamically allocated arrays. These are less error-prone than basic C++ arrays, as they provide features such as bounds checking and embed memory allocation/deallocation mechanisms. A vector allows automatic resizing of the array if necessary. However, such features come with a certain cost: Additional data is required to manage the container’s mechanism. Computation time is required to manage the container’s mechanism. In many cases, the overhead is negligible. More on STL containers later. Other solutions Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Y. Daniel Liang, Introduction to Programming with C++ (Chapter 7, 11), Peason, 2014, ISBN-13: Walter Savitch, Absolute C++ (Chapter 5, 7, 10, 19), Addison-Wesley, 2005, ISBN-13: Bjarne Stroustrup, The C++ Programming Language (Chapter 6, 7, 11), Addison-Wesley, 2013, ISBN-13: References Joey Paquet, COMP Advanced Program Design with C++