C HAPTER 03 Pointers Compiled by Dr. Mohammad Alhawarat.

Slides:



Advertisements
Similar presentations
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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.
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.
February 11, 2005 More Pointers Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Pointers and Dynamic Memory Allocation. Declaring a pointer.
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.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Pointer. lvalues In C++, any expression that refers to an internal memory location is called an lvalue Appear on left side of assignment statement e.g.
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.
P OINTERS A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Exception Handling How to handle the runtime errors.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
Chapter 9: Pointers.
Pointer.
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

C HAPTER 03 Pointers Compiled by Dr. Mohammad Alhawarat

W HAT S IZE S HOULD W E M AKE THE C HECKS A RRAY ? If it is too small, it might get filled up. If it is too large, many clients will only use a small fraction of the array space, and we will be wasting memory. The best approach might be to start an array off as small, then have it grow larger as more checks are written. This cannot be done with ordinary arrays, but it can be done with pointers and dynamically-allocated memory. 2

M EMORY T ERMINOLOGY variable name variable value address – a binary number used by the operating system to identify a memory cell of RAM It is important to know the precise meanings of these terms 3

M EMORY T ERMINOLOGY ( CONT.) 4 Addresses x 15

M EMORY T ERMINOLOGY ( CONT.) 5 Addresses x 15 Variable name

M EMORY T ERMINOLOGY ( CONT.) 6 Addresses x 15 A variable (which is a location)

M EMORY T ERMINOLOGY ( CONT.) 7 Addresses x15 Value of the variable

M EMORY T ERMINOLOGY ( CONT.) 8 Addresses x 15 Address of the variable

P OINTERS A pointer is a variable used to store an address The declaration of a pointer must have a data type for the address the pointer will hold (looks like this): int *ptr; char *chptr; 9

L OCATION B EHAVIOR A variable is a location When locations are used in code, they behave differently depending on whether or not they are used on the left side of an assignment If not used on the left side of an assignment, the value at the location is used When used on the left side of assignment, the location itself is used 10

A DDRESS - OF OPERATOR An address can be assigned to a pointer using the address-of operator &: int *ptr; int x; ptr = &x; 11

R ESULT 12 x ptr Addresses x ptr 01010

D EREFERENCE O PERATOR The dereference operator, *, is used on a pointer (or any expression that yields an address) The result of the dereference operation is a location (the location at the address that the pointer stores) Therefore, the way the dereference operator behaves depends on where it appears in code (like variables) 13

INT X = 3, * PTR ; 14 ptr x3

PTR = & X ; ( WHAT HAPPENS ?) 15 ptr x3

PTR = & X ; 16 ptr x3

Y = * PTR + 5; ( WHAT HAPPENS ?) 17 ptr x3 y

Y = * PTR + 5; 18 ptr x3 y8

INT Z = 5; 19 ptr x3 y8 z5

* PTR = 10 + Z ; ( WHAT HAPPENS ?) 20 ptr x y8 z5 3

* PTR = 10 + Z ; 21 ptr x y8 z5 15

* PTR = 10 + Z ; 22 ptr x y8 z5 15 Note that the value of x changes even though this line of code doesn’t contain x

A RRAYS The address of an array is the same as the address of the first element of the array. An array’s name (without using an index) contains the address of the array. The address of the array can be assigned to a pointer by assigning the array’s name to the pointer. An array name is not a pointer because the address in it cannot be changed (the address in a pointer can be changed). 23

T HE [ ] O PERATOR When an array is indexed, [ ] is an operator. For example, nums[3] produces the result *( nums + 3 ). C++ produces an address from the expression nums + 3, by: Noting what data type is stored at the address that nums contains Multiplying 3 by the number of bytes in that data type Adding the product onto the address stored in nums After the address is produced from nums + 3, it is dereferenced to get a location. 24

T HE H EAP The heap is a special part of RAM memory reserved for program usage. When a program uses memory from the heap, the used heap memory is called dynamically- allocated memory. The only way to dynamically allocate memory (use memory in the heap) is by using the new operator. 25

T HE NEW O PERATOR The new operator has only one operand, which is a data type. The new operation produces the address of an unused chunk of heap memory large enough to hold the data type (dynamically allocated) In order to be useful, the address must be assigned to a pointer, so that the dynamically allocated memory can be accessed through the pointer: int *ptr; ptr = new int; *ptr = 5; 26

INT * PTR ; 27 ptr

PTR = NEW INT ; 28 ptr

PTR = NEW INT ; 29 ptr

PTR = NEW INT ; 30 ptr Found a block in heap

PTR = NEW INT ; 31 ptr Replaces new operation

PTR = ; 32 ptr

PTR = ; 33 ptr

* PTR = 5; ( WHAT HAPPENS ?) 34 ptr

* PTR = 5; 35 ptr

D YNAMICALLY - ALLOCATED MEMORY Has no name associated with it (other locations have variable names associated with them) Can only be accessed by using a pointer The compiler does not need to know the size (in bytes) of the allocation at compile time The compiler does need to know the size (in bytes) of any declared variables or arrays at compile time 36

D YNAMIC A RRAYS The real advantage of using heap memory comes from using arrays in heap memory Arrays can be allocated by the new operator; then they are called dynamic arrays (but they have no name either) int *ptr; ptr = new int [5]; // array of 5 integer elements ptr[3] = 10; // using the [ ] operator 37

D YNAMIC A RRAYS ( CONT.) The size of a dynamic array does not need to be known at compile time: int numElements; cout << “How many elements would you like?“; cin >> numElements; float *ptrArr = new float [ numElements ]; 38

W HAT H APPENS AT THE E ND OF T HIS F UNCTION ? 1 void foo( ) 2 { 3 int numElements; 4 cout << 5 “How many elements would you like the array to have? “; 6 cin >> numElements; 7 float *ptrArr = new float [ numElements ]; 8 9 // the array is processed here 10 // output to the user is provided here 11 } 39

M EMORY L EAK All local variables and the values they contain are destroyed (numElements and ptrArr) The address of the dynamic array is lost BUT…the dynamic array is not destroyed The dynamic array can no longer be used, but the new operator will consider it as used heap memory (and cannot reuse it for something else). This is called memory leak. Memory leak is not permanent – it will end when the program stops. 40

M EMORY L EAK ( CONT.) Memory leak can easily be prevented during execution of a program. A program that continually leaks memory may run out of heap memory to use. Therefore, it is poor programming practice to allow memory leak to occur. 41

T HE DELETE O PERATOR 1 void foo( ) 2 { 3int numElements; 4cout << 5 “How many elements would you like the array to have? “; 6cin >> numElements; 7float *ptrArr = new float [ numElements ]; 8 9 // the array is processed here 10 // output to the user is provided here delete [ ] ptrArr; 13 } 42 Prevents memory leak – it frees the dynamic array so this memory can be reused by the new operator later on

T HE DELETE O PERATOR ( CONT.) When the delete operator is being used to free a variable pointed to by ptr: delete ptr; When the delete operator is being used to free an array pointed to by ptr: delete [ ] ptr; If you omit [ ] (common mistake), no compiler error will be given; however, only the first element of the array will be freed 43

A NOTHER C OMMON C AUSE OF M EMORY L EAK 44 First, pointer ptr is assigned the address of dynamically allocated memory. ptr

PTR = NEW INT ; ( WHAT HAPPENS ?) 45 ptr

PTR = NEW INT ; 46 ptr Unused block found in heap

PTR = ; 47 ptr

PTR = ; 48 ptr

PTR = ; 49 ptr The address of this block is not stored anywhere, but it hasn’t been freed – memory leak

A VOIDING M EMORY L EAK When you want to change the address stored in a pointer, always think about whether or not the current address is used for dynamically-allocated memory If it is (and that memory is no longer useful), use the delete operator before changing the address in the pointer; for example, delete ptr; 50

P OINTERS TO O BJECTS Pointers can be used to point to objects or arrays of objects: Check *chkptr = new Check; Check *chkarrptr = new Check [10]; The delete operator is used the same way: delete chkptr; delete [ ] chkarrptr; 51

R UNNING OUT OF H EAP M EMORY We can run out of heap memory if: We write poor code that continually allows memory leak while constantly using the new operator OR … If we use excessive amounts of heap memory If the new operator cannot find a chunk of unused heap memory large enough for the data type, the new operation throws an exception 52

C ODE FOR E XCEPTIONS 53 1int main( ) 2{ 3 char *ptr; 4 5 try { 6 ptr = new char[ ]; 7 } 8 9 catch( … ) { 10 cout << "Too many elements" << endl; 11 } return 0; 14} try clause catch clause

C ODE FOR E XCEPTIONS ( CONT.) 54 1int main( ) 2{ 3 char *ptr; 4 5 try { 6 ptr = new char[ ]; 7 } 8 9 catch( … ) { 10 cout << "Too many elements" << endl; 11 } return 0; 14} The program will crash if try/catch clauses are not written for code that ultimately causes an exception

A NOTHER E XAMPLE 55 1int main( ) 2{ 3Foo foo; 5try { 6foo.bar1( 35 ); 7foo.bar2( 10 ); 8foo.bar3( ); 9} 11catch ( … ) { 12cout << "Out of memory" << endl; 13} 15return 0; 16} These functions use the new operator.

A NOTHER E XAMPLE ( CONT.) 56 1int main( ) 2{ 3Foo foo; 5try { 6foo.bar1( 35 ); 7foo.bar2( 10 ); 8foo.bar3( ); 9} 11catch ( … ) { 12cout << "Out of memory" << endl; 13} 15return 0; 16} The client usually writes the exception- handling code to do whatever they wish to do.

A RRAY E XPANSION ptr size is 4 A dynamic array is filled, and more data needs to be put in. Therefore, the array needs to be expanded.

INT * TEMP = NEW INT [ SIZE * 2]; ptr size is 4

INT * TEMP = NEW INT [ SIZE * 2]; ptr size is 4 temp

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is 0

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is 0 5

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is 1 5

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is 1 5 7

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is 2 5 7

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp i is

FOR ( INT I = 0; I < SIZE ; I ++ ) TEMP [ I ] = PTR [ I ]; ptr size is 4 temp

DELETE [ ] PTR ; ptr size is 4 temp

DELETE [ ] PTR ; 71 ptr size is 4 temp

PTR = TEMP ; 72 ptr size is 4 temp

PTR = TEMP ; 73 ptr size is 4 temp

SIZE = SIZE * 2; 74 ptr size is 4 temp

SIZE = SIZE * 2; 75 ptr size is 8 temp

E XPANSION C OMPLETED 76 ptr size is Array is ready for more elements, using the same “array name”, ptr.