Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.

Slides:



Advertisements
Similar presentations
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.
Advertisements

@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 8 Dynamic Classes and the Law of the Big Three Instructor: Zhigang Zhu Department.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Reviews for Exam 1 Chapter 1-4 CS 211 Data Structures MHC, 2007.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic 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.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Xiaoyan Li, CSC211 Data Structures Lecture 10 The Bag and Sequence Classes with Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers & Dynamic Arrays Shinta P.
Pointers OVERVIEW.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
1 8. Run-Time Arrays — Intro. to Pointers For declarations like double doubleVar; char charVar = 'A'; int intVar = 1234; the compiler____________the object.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
Object-Oriented Programming in C++
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Slide 1 Chapter 10 Pointers and Dynamic Arrays. Slide 2 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers and Dynamic Arrays
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
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:
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Edgardo Molina, CSC212 Data Structure - Section AB Lecture 8 Dynamic Classes and the Law of the Big Three Instructor: Edgardo Molina Department.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Xiaoyan Li, CSC211 Data Structures Lecture 8 Dynamic Classes and the Law of the Big Three Instructor: Prof. Xiaoyan Li Department of Computer Science.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Data Structures in C++ Pointers & Dynamic Arrays Shinta P.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
@ George Wolberg, CSC212 Data Structure Lecture 6 Dynamic Classes and the Law of the Big Three Instructor: George Wolberg Department of Computer.
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Arrays
Dynamically Allocated Memory
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
CSC212 Data Structure - Section RS
9-10 Classes: A Deeper Look.
Presentation transcript:

pointers1 Pointers & Dynamic Arrays Allocating memory at run-time

pointers2 Review of pointers Pointer: variable that holds the address of a memory location as its value Pointers are used to indirectly reference the contents of the memory location memory p p2

pointers3 Review of pointers Each byte of memory is associated with a physical (numeric) address When a variable is declared, a set of bytes is allocated -- address of the first byte is address of the variable A pointer can reference this address

pointers4 Pointer declaration & use int n, *ip; // int variable & int // pointer declared n = 5;// initializes int variable ip = &n;// assigns address of n // to ip -- ip is now a // reference to n

pointers5 Pointer operations continued *ip = 7;// dereferences ip -- assigns new // value to memory ip points to (so // n = 7) *ip++;// adds 1 to n ip++;// moves pointer to next location -- // caution!!! -- in this instance, // pointer now references unknown // location

pointers6 Assignment operator & pointers Can assign address of ordinary variable to pointer of same type Can assign value of one pointer to another of same type Can assign content referenced by one pointer to content referenced by another char c, d, *e, *f; e = &c; f = &d;... e = f;... *f = *e;

pointers7 Summary of pointer operations Declaration: type *id1,*id2; Assignment: –address: id = &variable; –pointer: id2 = id1; // must be same type Dereferencing: –in assignment: *id2 = value; –in input/output: cin >> *id1; cout << *id1; Pointer arithmetic: id2++;

pointers8 Dynamic Variables Dynamic variable is neither declared nor initialized, and has no identifier -- only reference is through pointer Created at runtime (ordinary variables created at compile time) newOperator new used to allocate memory for dynamic variable

pointers9 Dynamic variable example double *dp;// declares pointer dp = new double; // allocates dynamic // memory *dp = 1.01;// assigns value to // unnamed dynamic // variable via pointer

pointers10 Dynamic Arrays Can use new to allocate entire array Pointer references first array index Array version especially useful because size of array can be left unspecified unitl runtime –can ask user for # of input elements –dynamic behavior = determined when program is running

pointers11 Dynamic Array Example int size, *nums; // size will hold array size; // nums will be used to // reference array elements cout << “How many values to input? “; cin >> size; nums = new int [size]; // creates array

pointers12 Dynamic arrays continued Dynamic array elements can be referenced just like static array elements -- use pointer name & index: nums[0], nums[1], etc. Once memory is allocated with new, it can’t be re-used until it is released with the delete operator: delete dp; // releases dynamic variable delete []nums; // releases dynamic array

pointers13 Pointers & arrays as parameters Pointers as value parameters –simulates pass by reference in C –can change value at memory location referenced by pointer, but can’t change pointer Array parameters –array name acts as pointer to first element –size need not be specified –changes to parameter affect actual argument

pointers14 Syntax for pass by value Pointers: type fname (type *pointer); –example: int f1 (int *ip); Arrays: type fname (type array[], type size); –example: int f2 (int nums[], size_t extent); –although it’s not required that we pass the size, it’s still handy to have it!

pointers15 Pointers & arrays as const parameters Pointer example: int cubit (const int *ip); –function can examine item referenced by ip –can’t change its value Array example: –double avg (const double data[], size_t size); –can examine & use values in data array, but can’t change them

pointers16 Pointers as reference parameters Use when: –need to change value of pointer (address pointer is referencing) –need this change to affect the actual parameter Example: function that assigns dynamic array to a pointer -- prototype below: void allocate_doubles (double*& p, size_t& n);

pointers17 Allocate_doubles function void allocate_doubles (double*& p, size_t& n) { cout << “Enter the number of spaces to allocate: “; cin >> n; p = new double[n]; } function use: double *dnums; size_t array_size; allocate_doubles (dnums, array_size);

pointers18 Using a dynamic array to create a container class -- Bag ADT II Original (static) bag: class Bag { … private: Item data [CAPACITY]; size_t used; }; Dynamic bag: class Bag { … private: Item* data; size_t used; size_t capacity; };

pointers19 Invariant for dynamic Bag Member variable used stores a count of the Items in the Bag Member variable data is a pointer to a dynamic array in which Items are stored Member variable capacity stores the current maximum size of the Bag

pointers20 Member functions in dynamic Bag Modifiers allocate dynamic memory as needed –constructor: sets Bag’s initial capacity –insert, += : allocate new, larger dynamic array if increased capacity is needed to perform operation –resize: new member function -- enlarges Bag -- used by insert & +=

pointers21 Member functions in dynamic Bag Value semantics: functions that determine how values are copied from one object to another -- can’t use automatic defaults with dynamic memory –assignment operator –copy constructor Both must be defined as Bag member functions

pointers22 Value semantics -- why not automatic? Suppose you have the following declaration: Bag x, y; and the following statement: x=y; Automatic assignment will copy values from y’s member variables to x, including: x.data = y.data; This doesn’t make a copy of the dynamic array -- instead, it just means there are now 2 pointers to the same dynamic array

pointers23 New member function: destructor Member function that returns dynamically allocated memory when no longer needed Always named ~name (ex. ~Bag( )) Has no parameters or return value Automatically activated when object becomes inaccessible Almost never called explicitly

pointers24 Destructor uses Local variable in a function -- if it is a dynamic object, the object’s destructor is called when the function returns Dynamic object passed by value to a function -- same as with local variable A dynamic variable of a dynamic object type is deleted

pointers25 Dynamic bag: class declaration & definitions class Bag { enum {DEF_CAP = 30}; // sets default capacity for bag -- can always be resized typedef char Item; Bag(size_t initCap = DEF_CAP); // constructor uses default argument so that user program // can set different initial size if desired Bag (const Bag& source); // copy constructor ~Bag( ); // destructor...

pointers26 Class declaration continued void resize ( size_t new_cap); // precondition: new_cap is a positive, non-zero integer // postcondition: Bag capacity is changed to new_cap; if // new_cap is less than used, Bag capacity = used void insert (const Item& entry); // postcondition: Item is inserted in the Bag; if doing so exceeds // Bag capacity, Bag is resized void remove (const Item& target); // postcondition: if target value is in the Bag, an instance of the // value is removed; if target value is not there, Bag is unchanged …

pointers27 Class declaration continued void operator += (const Bag& addend); // postcondition: contents of addend Bag have been added // to current Bag; if process causes current Bag capacity to be // exceeded, Bag is resized void operator = (const Bag& source); // postcondition: contents of current Bag are now identical to // contents of source Bag size_t size( ) const {return used}; size_t occurrences (const Item& target) const; // const functions are unchanged from static Bag...

pointers28 Class declaration continued friend Bag operator + (const Bag& b1, const Bag & b2); // unchanged from static Bag private: Item *data; // pointer to partially -filled dynamic array size_t used; // how much of array currently in use size_t capacity; // current Bag capacity };

pointers29 Bag member functions // default constructor Bag::Bag(size_t init_cap) { data = new Item[init_cap]; capacity = init_cap; used = 0; }

pointers30 Bag member functions // copy constructor Bag::Bag (const Bag& source) { data = new Item[source.capacity]; capacity = source.capacity; used = source.used; for (int n=0; n<used; n++) data[n] = source.data[n]; }

pointers31 Bag member functions // destructor Bag::~Bag( ) { delete [] data; }

pointers32 Bag member functions // resize void Bag::resize(size_t new_cap) { Item *larger;// temp pointer to new // larger array if (new_cap == capacity) return; // Bag is already the requested size...

pointers33 Resize function continued … if (new_cap < used) new_cap = used; // can’t shrink Bag smaller than what’s // already in use larger = new Item[new_cap]; // allocate sufficient memory for new array...

pointers34 Resize function continued … for (int n=0; n < used; n++) larger[n] = data[n]; delete [] data; data = larger; capacity = new_cap; }

pointers35 Insert function void Bag::insert(const Item& entry) { if (used == capacity) resize (used + 1); data[used] = entry; used++; }

pointers36 Remove function void Bag::remove(const Item& target) { int n; // will be index of target value for (n=0; (n<used) && (data[n]!= target); n++); // search array until target found or no more to search if (n == used) return; // quit if target not found used--; data[n] = data[used]; }

pointers37 Function operator += void Bag::operator += (const Bag& addend) { size_t addend_size = addend.used; if (used+addend_size > capacity) resize(used+addend_size); for (int n=0; n<addend_size; n++) { data[used] = addend.data[n]; used++; }

pointers38 Assignment operator void Bag::operator = (const Bag& source) { Item *new_data; if (capacity != source.capacity) { new_data = new Item[source.capacity]; delete [] data; data = new_data; capacity = source.capacity; } used = source.used; for (int n=0; n < used; n++) data[n] = source.data[n]; }

pointers39 Prescription for a dynamic class Some of the member variables are pointers Member functions allocate & release dynamic memory as needed Automatic value semantics must be overridden Class must have a destructor

pointers40 Copy constructor uses with a dynamic class When one object is initialized as a copy of another: Bag y(x); Bag y=x; When an object is returned from a function When a value parameter is an object

pointers41 Pointers & Dynamic Arrays Allocating memory at run-time