Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition

Slides:



Advertisements
Similar presentations
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Advertisements

Informática II Prof. Dr. Gustavo Patiño MJ
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
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.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: 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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Lesson 9 Pointers CS 1 Lesson 9 -- John Cole1. Pointers in Wonderland The name of the song is called ‘Haddock’s Eyes’.” “Oh, that’s the name of the song,
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified by use by the MSU CMPS Dept. Chapter 10:
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers Data Structures CSI 312 CSI Dept. Dr. Yousef Qawqzeh.
Pointers and Dynamic Memory Allocation
Yan Shi CS/SE2630 Lecture Notes
Dynamic Storage Allocation
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers.
Standard Version of Starting Out with C++, 4th Edition
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Lecture 9 Files, Pointers
Chapter 10: Pointers Starting Out with C++ Early Objects
Chapter 10: Pointers Starting Out with C++ Early Objects
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9: Pointers.
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers, Dynamic Data, and Reference Types
Constant pointers and pointers to constants
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
C++ Plus Data Structures
Standard Version of Starting Out with C++, 4th Edition
Dynamic Memory Allocation
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

Topics 10.1 Pointers and the Address Operator 10.2 Pointer Variables 10.5 Initializing Pointers 10.6 Comparing Pointers

C++ Data Types Simple Structured Address Integral Floating array struct union class char short int long enum Address pointer reference float double long double

10.1 Pointers and the Address Operator Each variable in a program is stored at a unique location in memory that has an address Use the address operator & to get the address of a variable: int num = -23; cout << &num; // prints address // in hexadecimal The address of a memory location is a pointer See pr10-01.cpp

10.2 Pointer Variables Pointer variable (pointer): a variable that holds an address Pointers provide an alternate way to access memory locations

Pointer Variables Definition: int *intptr; Read as: “intptr can hold the address of an int” or “the variable that intptr points to has type int” The spacing in the definition does not matter: int * intptr; int* intptr; * is called the indirection operator

Pointer Variables cout << intptr; // prints 0x4a00 Definition and assignment: int num = 25; int *intptr; intptr = &num; Memory layout: You can access num using intptr and indirection operator *: cout << intptr; // prints 0x4a00 cout << *intptr; // prints 25 *intptr = 20; // puts 20 in num num intptr 25 0x4a00 address of num: 0x4a00 See pr10-02.cpp, pr10-03.cpp and pr10-04.cpp

Another Example char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the right side has value 4000 // now p and q both point to ch 4000 A Z ch 5000 6000 4000 4000 q p

10.5 Initializing Pointers You can initialize to NULL or 0 (zero) int *ptr = NULL; You can initialize to addresses of other variables int num, *numPtr = &num; int val[ISIZE], *valptr = val; The initial value must have the correct type float cost; int *ptr = &cost; // won't work

The NULL Pointer There is a pointer constant called the “null pointer” denoted by NULL in cstddef. But NULL is not memory address 0. NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) { . . . // ok to use *ptr here }

Initializing Values in C++ 11 In C++ 11, putting empty { } after a variable definition indicates that the variable should be initialized to its default value C++ 11 also has the the key word nullptr to indicate that a pointer variable does not contain a valid memory location You can use int *ptr = nullptr; or int *ptr{ };

10.6 Comparing Pointers Relational operators can be used to compare the addresses in pointers Comparing addresses in pointers is not the same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // contents See pr10-10.cpp

Allocation of memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

3 Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program. static long SeedValue; AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function. What you have been doing up to now!! DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using unary operators new and delete

10.9 Dynamic Memory Allocation You can allocate storage for a variable while a program is running Use the new operator to allocate memory double *dptr; dptr = new double; new returns address of a memory location The data type of the variable is indicated after new

Using operator new If memory is available in an area called the free store (or heap), operator new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, the null pointer is returned. The dynamically allocated object exists until the delete operator destroys it. 16

Dynamic Memory Allocation You can also use new to allocate an array arrayPtr = new double[25]; The program may terminate if there is not sufficient memory You can then use [ ] or pointer arithmetic to access array

Dynamic Memory Example int *count, *arrayptr; count = new int; cout <<"How many students? "; cin >> *count; arrayptr = new int[*count]; for (int i=0; i<*count; i++) { cout << "Enter score " << i << ": "; cin >> arrayptr[i]; }

Releasing Dynamic Memory Use delete to free dynamic memory delete count; Use delete [] to free dynamic array memory delete [] arrayptr; Only use delete with dynamic memory! See pr10-14.cpp

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 1000 ptr ?

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; NOTE: Dynamic data has no variable name 1000 ptr ?

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; NOTE: Dynamic data has no variable name 1000 ptr ‘B’

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; NOTE: Dynamic data has no variable name 1000 ptr ‘B’ Displays B

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 1000 ptr NOTE: Delete deallocates the memory pointed to by ptr. ?

Dangling Pointers and Memory Leaks A pointer is dangling if it contains the address of memory that has been freed by a call to delete. Solution: set such pointers to NULL (or nullptr in C++ 11) as soon as the memory is freed. A memory leak occurs if no-longer-needed dynamic memory is not freed. The memory is unavailable for reuse within the program. Solution: free up dynamic memory after use

Memory Leak A memory leak occurs when dynamic memory (that was created using operator new) has been left without a pointer to it by the programmer, and so is inaccessible. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; How else can an object become inaccessible? 8 ptr -5 ptr2

Causing a Memory Leak int* ptr = new int; *ptr = 8; -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2

A Dangling Pointer occurs when two pointers point to the same object and delete is applied to one of them. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; 8 ptr -5 ptr2 FOR EXAMPLE,

Leaving a Dangling Pointer 8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; 8 ptr NULL ptr2

More on Memory Leaks General guidelines to avoid memory leaks: If a function allocates memory via new, it should, whenever possible, also deallocate the memory using delete If a class needs dynamic memory, it should allocate it using new in the constructor deallocate it using delete in the destructor See pr10-16.cpp

Some C++ pointer operations Precedence Higher -> Select member of class pointed to Unary: ++ -- ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate + - Add Subtract < <= > >= Relational operators == != Tests for equality, inequality Lower = Assignment

Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda