Managing 2D Arrays Simple Dynamic Allocation

Slides:



Advertisements
Similar presentations
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Advertisements

Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
C++ Review (3) Structs, Classes, Data Abstraction.
Pointers OVERVIEW.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Fall 2013CISC2200 Yanjun Li1 Review. Fall 2013CISC2200 Yanjun Li2 Outline Array Pointer Object-Oriented Programming.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 1 Composition: Cooperating Classes Composition.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Tables Data Structures & File Management Computer Science Dept Va Tech January 2004 ©2004 McQuain WD 1 Table Lookup Theoretically, looking up an item by.
C Programming Lecture 15 Two Dimensional Arrays. Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two.
Pointers and Dynamic Memory Allocation
Memory Management.
Operator Overloading CS 3370 – C++ Chapter 14.
Operator Overloading Introduction
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Dynamic Arrays
EGR 2261 Unit 10 Two-dimensional Arrays
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Motivation and Overview
Andy Wang Object Oriented Programming in C++ COP 3330
Operator overloading Conversions friend inline
Operator overloading Conversions friend inline
A First C++ Class – a Circle
Operator overloading Conversions friend inline
Pointers and Memory Overview
Pointers and Pointer-Based Strings
Passing Arguments to a Function
The dirty secrets of objects
Abstract Data Types and Encapsulation Concepts
Pointers and References
Dynamic Memory Allocation Reference Variables
C Passing arrays to a Function
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
Object Oriented Programming COP3330 / CGS5409
Pointers and dynamic objects
7 Arrays.
More About Data Types & Functions
1020: Introduction to Programming Mohamed Shehata November 22, 2017
4.9 Multiple-Subscripted Arrays
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
Multidimensional Arrays
7 Arrays.
Overloading functions
Pointers and Pointer-Based Strings
Arrays Arrays A few types Structures of related data items
Data Structures and Algorithms Introduction to Pointers
CS410 – Software Engineering Lecture #5: C++ Basics III
Pointers and dynamic objects
CS 144 Advanced C++ Programming February 12 Class Meeting
Class rational part2.
Pointers and References
Classes and Objects Object Creation
4.1 Introduction Arrays A few types Structures of related data items
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Managing 2D Arrays Simple Dynamic Allocation Passing a 2D Array to a Function Example: 2D Array Parameter Memory Layout for 2D Arrays There MUST be a Better Way 2D Array Encapsulation Array2D Construction and Destruction Array2D Use Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Simple Dynamic Allocation A 2-dimensional int array of any fixed size can be allocated and initialized as follows: const int Col = 4; int Row = 2; int (*A)[Col]; A = new int[Row][Col]; for (int i = 0; i < Row; i++) for (int j = 0; j < Col; j++) A[i][j] = i; Spec addition: in order to make your lives a bit easier, we will guarantee that the maze for MazeCrawler will never have more than 20 columns. Note: you must still allocate the array dynamically!! The primary shortcoming of the approach above is that the column dimension MUST be a constant. Passing a 2D array to a function also involves a requirement… Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Passing a 2D Array to a Function A 2-dimensional array parameter requires that the column dimension of the array be specified in the function prototype: Actual number of columns in array A. void init2D(int A[][C], int nRows, int nCols) { for (int i = 0; i < Row; i++) for (int j = 0; j < Col; j++) A[i][j] = i; } The reason relates to the manner in which the elements of the array A will be laid out in memory… Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Example: 2D Array Parameter #include <iostream> #include <iomanip> using namespace std; const int Col = 4; void init2D(int A[][Col], int nRows, int nCols) ; void main() { int Row = 2; int (*A)[Col]; A = new int[Row][Col]; init2D(A, Row, Col); for (int i = 0; i < Row; i++) { for (int j = 0; j < Col; j++) cout << setw(5) << A[i][j]; cout << endl; } void init2D(int A[][Col], int nRows, int nCols) { for (int i = 0; i < nRows; i++) for (int j = 0; j < nCols; j++) A[i][j] = i; Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Memory Layout for 2D Arrays First, physical memory is simply a one-dimensional array of bytes, indexed by addresses. C++ (like most languages) specifies that 2D arrays are to be mapped into this one-dimensional environment by storing the array cells row-by-row (known as row-major order). Assuming that the array has R rows and C columns, that results in a layout something like: 0,0 0,1 0,2 … 0,C-1 1,0 1,1 1,C-1 2,0 2,1 Assume address of the first byte here is 0x1000 Then the address of the 0-th cell of the second row depends on the number of elements in the first row (which is the number of columns in the matrix) and the size of each array element in bytes. When you make an array reference, like A[4][3], the compiler must generate code to calculate the address of the specified cell at runtime. The formula will necessarily involve the column dimension C of the matrix A. Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

There MUST be a Better Way Well… of course… but as usual, it’s a matter of picking which type of pain you wish to endure. One approach is to allocate an array of pointers, viewed say as pointers to the columns in a 2D matrix, and then use each pointer to dynamically allocate a column of the desired size. That’s syntactically (and conceptually) ugly but it WILL work. Another approach is to simply allocate a one-dimensional array, say A1D, of the correct total size and then treat it as a 2D array. How? By taking on the management of the array indexing arithmetic yourself. (See the previous memory layout again.) 0,0 0,1 0,2 … 0,C-1 1,0 1,1 1,C-1 2,0 2,1 This is cell 0 of a 1D array. This would be cell C of a 1D array. Now, if you want to logically refer to A[i][j], you just have to do some simple arithmetic to calculate the correct index k and refer to A1D[k] instead. Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

2D Array Encapsulation Of course, if you’re going to do that, there’s an advantage to be gained by wrapping the one-dimensional array inside a class and hiding all the messy translation details inside its member functions: class Array2D { private: int *Data; int nRows; // (logical) number of rows int nCols; // (logical) number of columns int Map(int R, int C) const; // translate [R][C] to right 1D index bool ValidRC(int R, int C) const; // check if [R][C] specify a cell public: Array2D(); Array2D(int R, int C); // allocate array of R*C cells Array2D(const Array2D& Source); // copy constructor and assignment Array2D& operator=(const Array2D& Source); bool Set(int R, int C, int Value); // store Value at A[R][C] (logically) int Get(int R, int C) const; // get Value at A[R][C] (logically) ~Array2D(); }; The idea is to allow the user to act as if there’s really a normal 2D array under the hood, while supporting pure dynamic allocation (no requirements that any dimension be a constant). Of course, we also provide protection against array bounds errors as well. Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Array2D Construction and Destruction The constructor will provide a (logical) 2D array with any dimensions: Array2D::Array2D(int R, int C) { nRows = R; nCols = C; Data = new int[nRows * nCols]; if (Data == NULL) { nRows = nCols = 0; } And destruction poses no new issues since Data is a simple one-dimensional array: Array2D::~Array2D() { delete [] Data; } Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Array2D Implementation The remainder of the implementation is left to the reader. A few notes… The copy constructor is necessary in order to pass Array2D objects as parameters or use them as return values. The assignment overload is not used in the following example, but it’s cheap to provide since a copy constructor must be written anyway. The function Map() that provides the translation from 2D to 1D indices is simple. Draw a few pictures and play around with indices and you’ll see the correct formula. The ValidRC() function does not use Map() (or any other translation code). It’s fairly trivial to turn Array2D into a template. Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Array2D Use #include <iostream> #include <iomanip> using namespace std; #include "Array2D.h" void init2D(Array2D& A, int Rows, int Cols); void print2D(const Array2D A, int Rows, int Cols, ostream& Out); void main() { int R = 3, C = 5; Array2D myArray(R, C); init2D(myArray, R, C); print2D(myArray, R, C, cout); } void init2D(Array2D& A, int Rows, int Cols) { int row, col; for (row = 0; row < Rows; row++) for (col = 0; col < Cols; col++) A.Set(row, col, row); // . . . continues . . . Computer Science Dept Va Tech January 2000 ©2000 McQuain WD

Array2D Use 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 // . . . continued . . . void print2D(const Array2D A, int Rows, int Cols, ostream& Out) { int row, col; for (row = 0; row < Rows; row++) { for (col = 0; col < Cols; col++) cout << setw(5) << A.Get(row, col); cout << endl; } 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 Computer Science Dept Va Tech January 2000 ©2000 McQuain WD