Lectures 6/7 Pointers and Dynamic Arrays

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

Dynamic Allocation of Memory

Exam 3 Chapters 7 & 9

Pointers, Dynamic Data, and Reference Types

Pointer Data Type and Pointer Variables

Dynamic Memory Allocation

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

CSC212 Data Structure - Section FG

DECLARAING AND INITIALIZING POINTERS

a data type is Types

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Mon, Jan 20, 2014

Pointers II. Class 31

Memory and Pointers written by Cathy Saxton

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

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

Array Elements as Function Parameters

CMSC202 Computer Science II for Majors

CSC1322 Object-Oriented Programming Concepts

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Chapter 9. Pointers and Dynamic Arrays

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

C++ for Java Programmers

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Structured Data. CIS 15 : Spring 2007

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

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

[0569] p 0318 garbage

CS201- Introduction to Programming Current Quizzes

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

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Programming in C/C Lecture 2

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

CSC 1300 Exam 4 Comprehensive-ish and Structs

Lectures 4 & 5 Container Classes

What is an algorithm?

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Homework #3 CS2255 Fall 2012

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Variables, Memory and Pointers

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

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

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

Ch 4 Pointers and Dynamic Arrays

CS201 Latest Solved MCQs

Lecture 6 Dynamic Classes and the Law of the Big Three. Instructor: George Wolberg Department of Computer Science City College of New York

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

IT 1033: Fundamentals of Programming Data types & variables

MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Dynamic Allocation of Memory

Pointers and Dynamic Arrays

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

CMSC 202 Midterm Exam 1 Fall 2015

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

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

CSc Introduction to Computing

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

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.

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 9 Linked Lists

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Object oriented programming C++

CSI33 Data Structures

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

CSC212 Data Structure - Section FG

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

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

C++ Programming Chapter 7 Pointers

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

Lecture 3 ADT and C++ Classes (II)

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

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

Memory and C++ Pointers

Launchpad Lecture -10

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

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

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

BITG 1113: POINTER LECTURE 12

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

CS242 COMPUTER PROGRAMMING

6. Pointers, Structs, and Arrays. 1. Juli 2011

Lab 3. Pointers Programming Lab (Using C) XU Silei

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

Topics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays)

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Memory, Arrays, and Parameters

Computer Programming

CS2255 HOMEWORK #1 Fall 2012

Arrays, Pointers and Memory Management

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

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.

Chapter 2. Procedural Programming

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

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Computer Programming

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Pointers. Variable Declaration. Chapter 10

Transcription:

CSC212 Data Structure - Section FG Lectures 6/7 Pointers and Dynamic Arrays Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1

Why Pointers and Dynamic Memory Limitation of our bag class bag::capacity constant determines the capacity of every bag wasteful (if too big) and hard to reuse (if too small) need to change source code and recompile Solution: provide control over size in running time <= dynamic arrays <= pointers and dynamic memory @ Feng HU, 2016 2

Outline (Reading Ch 4.1 4.2) Pointers *(asterisk) and &(ampersand) operators Dynamic Variables and new Operator Dynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memory Garbage Collection and delete Operator Parameters revisited Pointers and Arrays as Parameters @ Feng HU, 2016 3

Pointer Variable First let s have a look at local variables int i; By this declaration, a cell of 4 adjacent bytes (in some machines) are allocated in the local memory (called stack memory) Q: What s the value of i? @ Feng HU, 2016 4 904 908 912 916? Address 9## is just for illustration. Real address may have 64 bits i

Pointer Variable First let s have a look at local variables int i; i = 42; The assignment put number 42 in the cell. The memory address of the 1 st byte is the address of the variable i 904 908 912 916 42 i the pointer to i Q: How to get the address? @ Feng HU, 2016 5

Pointer Variable First let s have a look at local variables int i; i = 42; 904 42 i cout << &i; & (ampersand) operator - address of operator - &i is! 908 912 916 -Note: two meanings of & Q: Where can we store &i? @ Feng HU, 2016 6

Pointer Variable The memory address can be stored a special pointer variable int i=42; int *i_ptr; 1. the type of the data that the pointer points to: int 2. an asterisk (*) 3. the name of the newly declared pointer: i_ptr Q: How to point i_ptr to i? 904 908 912 916 42? i i_ptr @ Feng HU, 2016 7

Pointer Variable Assign the address of i to i_ptr 42 i int i=42; int *i_ptr; i_ptr = &i; 904 908 912 916? i_ptr What are the results of - cout << i; - cout << i_ptr; - cout << &i_ptr; @ Feng HU, 2016 8

Pointer Variable The i_ptr holds the address of an integer, not the integer itself 42 i int i=42; int *i_ptr; i_ptr = &i; Two ways to refer to i - cout << i; - cout << *i_ptr; - dereferencing operator * - two meanings of * 904 908 912 916 i_ptr @ Feng HU, 2016 9

Operators * and & Operator * Pointer declaration int *i_ptr; dereferencing operator cout << *i_ptr; Two different meanings! Operator & Reference parameter void funct(int& i); address of operator i_ptr = &i; Just coincidence? Will see in parameter passing @ Feng HU, 2016 10

Syntax and Naming Issues How to declare two pointers in a line char *c1_ptr, *c2_ptr; instead of char* c1_ptr, c2_ptr; For clarity, use _ptr or cursorfor pointer variables @ Feng HU, 2016 11

Assignment Operators with Pointers p2 = p1 42 i 904? p1 int i = 42; int *p1, *p2; p1 = &i; p2 = p1; address value name 42 i 908 912 916? p2 904? p1 908? p2 Both p1 and p2 point to the same integer @ Feng HU, 2016 12

Assignment Operators with Pointers *p2 = *p1 42 i 904? p1 int i = 42; int *p1, *p2; p1 = &i; *p2 = *p1; X address value name 42 i 908 912 916? p2 904? p1 908? p2 p2 doesn t point to anywhere, so assigning value to *p2 will cause a running time error! @ Feng HU, 2016 13

Assignment Operators with Pointers *p2 = *p1 42 i 904 42 20 j int i = 42; int j = 20; int *p1, *p2; p1 = &i; 42 i 904 42 20 j 908 912 916? 904? p1 p2 p2 = &j; *p2 = *p1; 908? p1 912 904? p2 Both i (*p1) and j (*p2) will have the same integer values @ Feng HU, 2016 14

Outline (Reading Ch 4.1 4.2) Pointers *(asterisk) and &(ampersand) operators Dynamic Variables and new Operator Dynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memory Garbage Collection and delete Operator Parameters revisited Pointers and Arrays as Parameters @ Feng HU, 2016 15

Dynamic Variables We cannot use a pointer if not initialized need to point to a declared variable How to use a pointer without connecting with a declared ordinary variable? Solution: Dynamic (allocated) variables not declared, therefore no identifier created during execution Real power of pointers is with dynamic variables @ Feng HU, 2016 16

The new Operator allocates memory and return a pointer int *p1; p1 = new int; *p1 = 20; 10500? p1 20?? 904 908 10500? p1 - p1 points to a dynamic integer variable without any identifier (name) - dynamic memory comes from the programs heap (free store) @ Feng HU, 2016 17 10492 10496 10500 20?

Dynamic Arrays new can allocate an entire array all at once int *p1; p1 = new int[4]; p1[2] = 20; cout<<*(p1+2); 10488? p1 20 904 908 10488? p1 - p1 points to 1st entry of dynamic array 10488? - number of entries in a pair of sq. brackets - two ways to access p1 (array or pointer) 10492 10496 10500 20 @ Feng HU, 2016 18

Accessing Dynamic Array Use array notation the 1 st entry p1[0] = 18; the 3 rd entry p1[2] = 20; the ith entry p1[i-1] = 19; Use pointer notation the 1 st entry *p1 = 18; the 3 rd entry *(p1+2) = 20; the ith entry *(p1+i-1) = 19; A demo for pointers and dynamic arrays: test_pointer.cxx @ Feng HU, 2016 19

Dynamic Array Example:Quiz A program read ages of each of CCNY classes, with varying sizes, calculate the average, and then print out the average. size_t size; int *ages; float average; cin >> size; ages = new int[size]; // input ages of all students // calculate average // print average @ Feng HU, 2016 20

Dynamic Objects of a class new can also allocate a dynamic object point *p1; p1 = new point(1.0, 2.0); cout<< (*p1).get_x(); cout<< p1->get_x();? p1 10496 1.0 2.0 904 908 10496? p1 - p1 points to dynamic object without name 10488 - parameters can be used as in declaration - two ways to access p1 (* and ->) 10492 10496 10500 1.0 2.0? @ Feng HU, 2016 21

Dynamic Object Arrays of a class V X V Q: Are the followings correct? point3 demo Ten points with default coordinates? p1 = new point[10]; Ten points with the same coordinates? p1 = new point(1.0, 2.0)[10]; Ten points on the x axis with interval 1? p1 = new point[10]; for (i=0; i<10; i++) p1[i].set(i, 0); Assume we have a member function void point::set(double x_init, double y_init); @ Feng HU, 2016 22

Failure of the new Operator Dynamic memory via new operator comes from heap of a program Heap size from several K to 1GB, however fixed Could run out of room therefore cause a bad_alloc exception error message and program halts Good practice 1: document which functions uses new Good practice 2: garbage collection by delete operator @ Feng HU, 2016 23

Outline (Reading Ch 4.1 4.2) Pointers *(asterisk) and &(ampersand) operators Dynamic Variables and new Operator Dynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memory Garbage Collection and delete Operator Parameters revisited Pointers and Arrays as Parameters @ Feng HU, 2016 24

The delete Operator Release any dynamic memory (heap memory) that is no longer needed int *i_ptr; double *d_ptr; point *p_ptr; delete i_ptr; delete [ ] d_ptr; // empty brackets delete p_ptr; i_ptr = new int; d_ptr = new double[20]; p_ptr = new point(1.0, 2.0); Questions( true or false): 1. delete resets these pointers 2. delete removes dynamic objects pointed by the pointers 3. nothing happens to the pointers themselves @ Feng HU, 2016 25 X V V

Outline (Reading Ch 4.1 4.2) Pointers *(asterisk) and &(ampersand) operators Dynamic Variables and new Operator Dynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memory Garbage Collection and delete Operator Parameters revisited Pointers and Arrays as Parameters @ Feng HU, 2016 26

Pointers and Arrays as Parameters Value parameters that are pointers Array parameters Pointers and arrays as const parameters Reference parameters that are pointers @ Feng HU, 2016 27

Value parameters that are pointers Compare ordinary and pointer variables void print_int_42(int i) { cout << i<<endl ; i = 42 ; cout << i <<endl; } void set_int_42(int* i_ptr) { cout << *i_ptr <<endl; *i_ptr = 42 ; cout << *i_ptr <<endl; } 80 42 80 Calling program: int m = 80; print_int_42(m); cout << m<<endl<<endl; 80 42 42 set_int_42(&m); cout << m<<endl<<endl; @ Feng HU, 2016 28

Array Parameters Compare ordinary and Dynamic arrays Calling program: int ages[30]; make_all_20(ages, 30); Calling program: void make_all_20(int data[ ], size_t size) { for (int i = 0 ; i< size; i++) { data[i] = 20; } } int *ages; ages = new int[30] make_all_20(ages, 30); - An array parameter automatically treated as pointer to the first entry ( value or reference?) - In the function prototype and implementation, size of the array is not specified inside bracket but by another parameter @ Feng HU, 2016 29

Pointers or Array as const Parameters to make sure they will not be changed Protoptyes: bool is_20(const int* i_ptr); double average(const int data[ ], size_t size); Calling program: int *ages, *i_ptr; double aver_age; ages = new int [ 30 ];... aver_age = average(ages, 30); i_ptr = &ages[12]; // i_ptr = (ages+12); if (is_20(i_ptr)) cout << Sudent No. 13 is 20! <<endl; @ Feng HU, 2016 30

Reference Parameters that are Pointers if we want to change the pointer to a new location void allocate_int_arrary(int* i_ptr, size_t size) { i_ptr = new int[size]; } X Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << address that ages points to is << ages<<endl; allocate_int_array(ages, 30); cout << address that ages points to is << ages<<endl; @ Feng HU, 2016 31

Reference Parameters that are Pointers if we want to change the pointer to a new location void allocate_int_arrary(int*& i_ptr, size_t size) { i_ptr = new int[size]; } V Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << address that ages points to is << ages<<endl; allocate_int_array(ages, 30); cout << address that ages points to is << ages<<endl; @ Feng HU, 2016 32

Reference Parameters that are Pointers if we want to change the pointer to a new location typedef int* integer_ptr; void allocate_int_arrary(integer_ptr& i_ptr, size_t size) { i_ptr = new int[size]; } V Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << address that ages points to is << ages<<endl; allocate_int_array(ages, 30); cout << address that ages points to is << ages<<endl; @ Feng HU, 2016 33

Reading and Programming Assignments Reading before the next lecture Chapter 4. Sections 4.3-4.4 Programming Assignment 2 Detailed guidelines online! Due September 28 (Wednesday) @ Feng HU, 2016 34