DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Similar documents
INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Chapter 7 Array. Array. C++, How to Program

Dynamic Allocation of Memory

Summer May 18, 2010

Exam 3 Chapters 7 & 9

Homework #3 CS2255 Fall 2012

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

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

Fundamental of Programming (C)

Dynamic Allocation of Memory

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Pointers, Dynamic Data, and Reference Types

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

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

C++ for Java Programmers

Pointers II. Class 31

CS201- Introduction to Programming Current Quizzes

Call The Project Dynamic-Memory

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

Chapter 9. Pointers and Dynamic Arrays

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

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

Pointers. Pointers. Pointers (cont) CS 217

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold


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

CS 161 Exam II Winter 2018 FORM 1

COMP 11 Class 17 Outline

Pointers! Arizona State University 1

Homework 4. Any questions?

Pointers. Memory. void foo() { }//return

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

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

CPSC 427: Object-Oriented Programming

Financial computing with C++

CPSC 427: Object-Oriented Programming

Common Misunderstandings from Exam 1 Material

primitive arrays v. vectors (1)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Linked List using a Sentinel

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

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Arrays. Week 4. Assylbek Jumagaliyev

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

CS201 Some Important Definitions

Lecture 15a Persistent Memory & Shared Pointers

Launchpad Lecture -10

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

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

Introducing C++ to Java Programmers

C++ Programming Chapter 7 Pointers

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Run Time Environment

Variables, Memory and Pointers

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Arrays and Pointers in C. Alan L. Cox

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

Lecture on pointers, references, and arrays and vectors

Solution Manual for Data Structures and Problem Solving Using C++ 2nd edition by Mark A. Weiss

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CSI33 Data Structures

Object-Oriented Programming for Scientific Computing

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Pointers. Pointer References

Pointers and Strings Prentice Hall, Inc. All rights reserved.

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

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

Course organization. Course introduction ( Week 1)

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Homework Assignment #2 (revised)

Introduction to C++ with content from

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

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

Chapter 2. Procedural Programming

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CS24 Week 3 Lecture 1

a data type is Types

Introduction to Programming. Lecture 6: Functions & Program Structure

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

Constants, References

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

FORM 2 (Please put your name and form # on the scantron!!!!)

Memory, Arrays, and Parameters

Transcription:

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY Pages 800 to 809 Anna Rakitianskaia, University of Pretoria

STATIC ARRAYS So far, we have only used static arrays The size of a static array must be fixed at compile time: int array[10]; // create a 10-element array The following is illegal with a static array: cout << "How many variables do you want? "; int nvars; cin >> nvars; int array[nvars]; // wrong! // The size of the array must be a constant How would you choose array size at run time?

DYNAMIC ARRAYS Dynamic arrays are allocated on the heap using the new keyword: int *arrayptr = new int[10]; // create a 10-element array dynamically The following is possible now: cout << "How many variables do you want? "; int nvars; cin >> nvars; int *array = new int[nvars]; // correct! Pointer array now points to the first element of the array we have just created

ARRAYS & POINTER ARITHMETIC Both static and dynamic array variables store the address of the first array element Static: int array[5]; Dynamic: int *array = new int[5]; array 1000 address array[0] 1000 array[1] 1004 array[2] 1008 array[3] 1012 array[4] 1016 memory

ARRAYS & POINTER ARITHMETIC Pointer arithmetic can be used to iterate through an array: const int arraysize = 7; int array[arraysize]; for (int *p = array; p < array + arraysize; p++) *p = 0; // Pointer p points at the current element; // Dereferencing p accesses the element; // Incrementing p moves p to the next el.

ARRAYS & POINTER ARITHMETIC Traverse a dynamic array using pointer arithmetic: int *array = new int[arraysize]; for (int *el = array; el < array + arraysize; el++) *el = 0; // set every element to 0 Traverse a dynamic array using subscripts: int *array = new int[arraysize]; for (int i = 0; i < arraysize; i++) array[i] = 0; // set every element to 0 The subscript access to dynamic array elements is implemented using pointer arithmetic: array[ i ] == * ( array + i )

DYNAMIC TWO-DIMENSIONAL ARRAYS Static two-dimensional: int a[3][3]; a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] Dynamic two-dimensional: a dynamic array of dynamic arrays (a pointer to an array of pointers) memory array[0] * a[0][0] a[0][1] a[0][2] array[1] * a[1][0] a[1][1] a[1][2] array[2] * a[2][0] a[2][1] a[2][2]

DYNAMIC TWO-DIMENSIONAL ARRAYS To declare a two dimensional array, we first declare an array of pointers (rows), and then declare every row to be an array of columns: int **a = new int * [3]; // rows for(int row = 0; row < 3; row++) a[row] = new int[3]; // columns memory a 1000 a[0] * a[0][0] a[0][1] a[0][2] a[1] * a[1][0] a[1][1] a[1][2] a[2] * a[2][0] a[2][1] a[2][2]

DYNAMIC TWO-DIMENSIONAL ARRAYS Individual elements of a 2D dynamic array can still be accessed through double indices: for(int row = 0; row < 3; row++) for(int col = 0; col < 3; col++) cout << a[row][col] << endl; To deallocate all pointers, you have to loop through the array: for(int row = 0; row < 3; row++) delete [] a[row]; delete [] a;

DYNAMIC TWO-DIMENSIONAL ARRAYS Standard main function signature: int main(int argc, char** argv)... argc number of command line parameters argv an array of parameters, where every parameter is an array of characters./test param1 param2 param3

POINTERS & FUNCTIONS Pass by value Pass by reference void dostuff(int x) x++; int y = 42; dostuff(y); cout << y << endl; // The output is 42 : // y has not being // modified void dostuff(int &x) // Notice the & x++; int y = 42; dostuff(y); cout << y << endl; // The output is 43 : // y has being modified!

POINTERS & FUNCTIONS Pointer parameter: Pass by value void dostuff(int * x) *x = 42; // *x can be modified, // but x (address) can // not be modified Pointer parameter: Pass by reference void dostuff(int * &x) *x = 42; x = NULL; // Both *x and x // can be modified Pass by pointer: Even though the pointer address can not be modified when a pointer is passed by value, the value of the memory location to which the pointer points can still be modified thus, passing a pointer by value is similar to passing the value that it points to by reference

POINTERS & FUNCTIONS Pass by pointer Pass by reference void dostuff(int *x) (*x)++; int y = 42; dostuff(&y); cout << y << endl; // The output is 43 : // y has being modified! void dostuff(int &x) x++; int y = 42; dostuff(y); cout << y << endl; // The output is 43 : // y has being modified!

POINTERS & FUNCTIONS Return type of a function can be a pointer: we might want to return the address, not the value However, returning an address of a local variable will result in an error: int* multbytwo(int n) int nvalue = n * 2; int *p = &nvalue; // get the address of nvalue return p; // return the pointer // nvalue goes out of scope here! // Our pointer is useless now...

POINTERS & FUNCTIONS Pointers to dynamically allocated memory can be safely returned: dynamic variables have no scope Useful example: returning a dynamic array int* allocatearray(int nsize) int *x = new int[nsize]; return x; int main() int *array = allocatearray(25); // do stuff with array delete[] array; return 0;

SHALLOW VS DEEP COPY & POINTERS Shallow Copy Copy the address of one variable into another variable Two variables refer to the same data stored in the same location in memory Deep Copy Make a copy of the data and assign this data to a new variable Two variables refer to two different locations in memory where the same data is stored x y data x y data data

SHALLOW COPY & POINTERS Assigning a pointer to another pointer creates a shallow copy: int *first = new int[nsize]; // fill array with data int *second = first; // now both first and second store the same address, // but the array is stored in memory once:

SHALLOW COPY & POINTERS If we delete either of the two pointers, both will be dangling: delete [] second; // The data has been deleted, // even though first still points to it!

DEEP COPY & POINTERS To make a deep copy of an array, iterate through it: int *first = new int[nsize]; // fill array with data int *second = new int[nsize]; for(int i = 0; i < nsize; i++) second[i] = first[i];

QUESTION TIME Next lecture: Classes & pointers