Pointers and Dynamic Variables

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Writing a Good Program 8. Elementary Data Structure.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Object-Oriented Programming in C++
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stacks And Queues Chapter 18.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
Data Structures & Algorithms
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Memory Management.
Object Lifetime and Pointers
Dynamic Storage Allocation
Stack: a Linked Implementation
18 Chapter Stacks and Queues
Chapter 18: Stacks and Queues.
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Data Structures Interview / VIVA Questions and Answers
Pointers Revisited What is variable address, name, value?
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
LINKED LISTS CSCD Linked Lists.
Dynamically Allocated Memory
CMSC 341 Lecture 5 Stacks, Queues
Pointers and Linked Lists
Dynamic Memory Allocation
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Linked Lists.
Stacks, Queues, and Deques
Chapter 19: Stacks and Queues.
Arrays and Linked Lists
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers and Dynamic Variables
Linked List (Part I) Data structure.
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
18.5 Linked Queues Like a stack, a queue can be implemented using pointers and nodes Allows dynamic sizing, avoids issue of wrapping indices NULL front.
Dynamic Memory A whole heap of fun….
Arrays an array of 5 ints is filled with 3,2,4,1,7
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Lists.
Dynamic Memory And Objects
Stacks, Queues, and Deques
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
Classes and Objects Object Creation
Presentation transcript:

Pointers and Dynamic Variables

Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new operator * Save an address in a pointer * Understand where dynamically allocated data is stored Know how and when to delete dynamically allocated data Understand how to build a dynamic stack implementation

Dynamic Memory Allocation Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5; . . . } int main ( ) this is a global variable it is stored in the data segment. this is a local variable it is stored on the stack.

Dynamic Memory Allocation Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5; . . . } int main ( ) valueOne exists for the entire life of the program. valueTwo comes into existence when it is declared, and disappears when the function ends.

What if you want to control when a variable comes into existence, and when it goes away?

The new operator int* a = new int; This is a pointer. This variable is stored on the heap. Storage from the heap is allocated dynamically as your program executes, int* a = new int; CoinBank* myBank = new CoinBank(5,3); These variables come into existence when they are declared. They don’t have names, but are accessed through pointers. They exist and take up memory until explicitly deleted.

Some languages, like Java and C# have a garbage collector to clean up data on the heap that is no longer in use. C++ does not – you have to do it!

delete Dynamically allocated variables will stay around until you explicitly delete them. Thus, they are completely under programmer control. To delete a dynamically allocated variable you would write delete a; where a is a pointer to the variable. When dynamically allocated variables are not properly deleted, your program will have a “memory leak”, which is really bad.

Dynamic Arrays Recall that when we talked about arrays, we noted that the array size given in the array declaration had to be a constant value. That is, the array size had to be fixed at compile time. This presents some difficulties: * either we guess too low and the array is not big enough to hold all of the data required, or * we guess to high and we waste space because elements of the array are not used.

One approach to solving this problem is to allocate the storage required for the array at run-time. int size; cout << “How big is the array?”; cin >> size; int *myArray; myArray = new int [size]; since we are allocating storage at run-time, we are allowed to use a variable as the array size.

Now, remembering the relationship between an array name and a pointer, we can use the dynamic array just like a normal array… myArray [5] = 15; cout << myArray[n]; Remember, myArray is just the name of the pointer where we saved the address returned by the new operator.

delete [ ] Whenever you use [ ] with new to allocate an array dynamically, you must use the corresponding form of the delete, delete [ ]. That is, if you write int *myArray; myArray = new int [10]; You must write delete [ ] myArray; to delete the array!

If you do not delete dynamically allocated data when you are done with it, your program may crash and it has the potential to crash your computer.

The -> Operator When we dynamically allocate storage for an object, we no longer use the dot operator to access its data members. Instead we use the -> operator. piggyBankPtr = new PiggyBank; piggyBankPtr->moneyInBank = 12.45;

The pointer “this” Every object contains a data member named this, that contains the address of the object itself.

The pointer ‘this’ So, in the function myCircle.getArea( ); You could write double Circle::getArea( ) { return this->radius * this->radius * PI; } i.e. this->radius refers to the radius data member in the object receiving the getArea message.

18.2 Dynamic Stacks Implemented as a linked list Can grow and shrink as necessary Can't ever be full as long as memory is available

Dynamic Linked List Implementation Define a class for a dynamic linked list Within the class, define a private member class for dynamic nodes in the list Define a pointer to the beginning of the linked list, which will serve as the top of the stack

Linked List Implementation A linked stack after three push operations: push('a'); push('b'); push('c'); c b a NULL top

Operations on a Linked Stack Check if stack is empty: bool isEmpty() { if (top == NULL) return true; else return false; }

Operations on a Linked Stack Add a new item to the stack void push(char x) { top = new LNode(x, top); }

Operations on a Linked Stack Remove an item from the stack char pop( ) { if (isEmpty()) { // throw error } char x = top->value; LNode *oldTop = top; top = top->next; delete oldTop; return x; } See DynIntStack.h, DynIntStack.cpp, pr18-03.cpp