CSC 2100. Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.

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

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.
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.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.
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.
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.
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.
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.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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.
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.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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 © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
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 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.
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.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
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.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
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.
Pointers and Arrays Dynamic Variables and Arrays.
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.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Pointers and Dynamic Memory Allocation
Dynamic Storage Allocation
Imagine a tollbooth at a bridge
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
8 Pointers.
Data Structures Unit-1 Engineered for Tomorrow CSE, MVJCE.
Dynamically Allocated Memory
Pointers and References
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Objectives You should be able to describe: Addresses and Pointers
Dynamic Memory.
Pointers and References
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

CSC 2100

Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures CSC Data Structures/Algorithms2

Addresses and Pointers C++ allows two ways of accessing variables Name (C++ keeps track of the address of the first location allocated to the variable) Address/Pointer Symbol & gets the address of the variable that follows it Addresses/Pointers can be displayed by the cout statement Addresses displayed in HEXADECIMAL CSC Data Structures/Algorithms3

Example #include void main( ) { int data = 100; float value = 56.47; cout << data << &data << endl; cout << value << &value << endl; } Output: 100 FFF FFF0 CSC Data Structures/Algorithms FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 value data

Pointer Variables The pointer data type A data type for containing an address rather than a data value Integral, similar to int Size is the number of bytes in which the target computer stores a memory address Provides indirect access to values CSC Data Structures/Algorithms5

Declaration of Pointer Variables A pointer variable is declared by: dataType *pointerVarName; The pointer variable pointerVarName is used to point to a value of type dataType The * before the pointerVarName indicates that this is a pointer variable, not a regular variable The * is not a part of the pointer variable name CSC Data Structures/Algorithms6

Declaration of Pointer Variables (Cont..) Example int *ptr1; float *ptr2; ptr1 is a pointer to an int value i.e., it can have the address of the memory location (or the first of more than one memory locations) allocated to an int value ptr2 is a pointer to a float value i.e., it can have the address of the memory location (or the first of more than one memory locations) allocated to a float value CSC Data Structures/Algorithms7

Declaration of Pointer Variables (Cont..) Whitespace doesn’t matter and each of the following will declare ptr as a pointer (to a float ) variable and data as a float variable float *ptr, data; float (*ptr), data; float data, *ptr; CSC Data Structures/Algorithms8

Assignment of Pointer Variables A pointer variable has to be assigned a valid memory address before it can be used in the program Example: float data = 50.8; float *ptr; ptr = &data; This will assign the address of the memory location allocated for the floating point variable data to the pointer variable ptr. This is OK, since the variable data has already been allocated some memory space having a valid address CSC Data Structures/Algorithms9

Assignment of Pointer Variables (Cont..) CSC Data Structures/Algorithms10 float data = 50.8; float *ptr; ptr = &data; 50.8 FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 data

Assignment of Pointer Variables (Cont..) CSC Data Structures/Algorithms11 float data = 50.8; float *ptr; ptr = &data; 50.8 FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data

Assignment of Pointer Variables (Cont..) CSC Data Structures/Algorithms12 float data = 50.8; float *ptr; ptr = &data; FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data

Assignment of Pointer Variables (Cont..) Don’t try to assign a specific integer value to a pointer variable since it can be disastrous float *ptr; ptr = 120; CSC Data Structures/Algorithms13 You cannot assign the address of one type of variable to a pointer variable of another type even though they are both integrals int data = 50; float *ptr; ptr = &data;

Initializing pointers A pointer can be initialized during declaration by assigning it the address of an existing variable float data = 50.8; float *ptr = &data; If a pointer is not initialized during declaration, it is wise to give it a NULL (0) value int *ip = 0; float *fp = NULL; CSC Data Structures/Algorithms14

The NULL pointer The NULL pointer is a valid address for any data type. But NULL is not memory address 0. 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. CSC Data Structures/Algorithms15

Dereferencing Dereferencing – Using a pointer variable to access the value stored at the location pointed by the variable Provide indirect access to values and also called indirection Done by using the dereferencing operator * in front of a pointer variable Unary operator Highest precedence CSC Data Structures/Algorithms16

Dereferencing (Cont..) Example: float data = 50.8; float *ptr; ptr = &data; cout << *ptr; Once the pointer variable ptr has been declared, *ptr represents the value pointed to by ptr (or the value located at the address specified by ptr ) and may be treated like any other variable of float type CSC Data Structures/Algorithms17

Dereferencing (Cont..) The dereferencing operator * can also be used in assignments. *ptr = 200; Make sure that ptr has been properly initialized CSC Data Structures/Algorithms18

Dereferencing Example CSC Data Structures/Algorithms19 #include void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output: FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data

Dereferencing Example (Cont..) CSC Data Structures/Algorithms20 #include void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output: FFF FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data

Dereferencing Example (Cont..) CSC Data Structures/Algorithms21 FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data #include void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output:

Dereferencing Example (Cont..) CSC Data Structures/Algorithms22 FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data #include void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output: 27.4

Dereferencing Example (Cont..) CSC Data Structures/Algorithms23 FFF FFF1 FFF0 FFF2 FFF3 FFF4 FFF5 FFF6 ptr data #include void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output: 27.4

Operations on Pointer Variables Assignment – the value of one pointer variable can be assigned to another pointer variable of the same type Relational operations - two pointer variables of the same type can be compared for equality, and so on Some limited arithmetic operations integer values can be added to and subtracted from a pointer variable value of one pointer variable can be subtracted from another pointer variable CSC Data Structures/Algorithms24

Pointers to arrays A pointer variable can be used to access the elements of an array of the same type. int gradeList[8] = {92,85,75,88,79,54,34,96}; int *myGrades = gradeList; cout << gradeList[1]; cout << *myGrades; cout << *(myGrades + 2); cout << myGrades[3]; Note that the array name gradeList acts like the pointer variable myGrades. CSC Data Structures/Algorithms25

CSC Data Structures/Algorithms26 Dynamic Memory Allocation

Types of Program Data Static Data: Memory allocation exists throughout execution of program Automatic Data: Automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function Dynamic Data: Explicitly allocated and deallocated during program execution by C++ instructions written by programmer CSC Data Structures/Algorithms27

Allocation of Memory Static Allocation: Allocation of memory space at compile time. Dynamic Allocation: Allocation of memory space at run time. CSC Data Structures/Algorithms28

Dynamic memory allocation Dynamic allocation is useful when arrays need to be created whose extent is not known until run time complex structures of unknown size and/or shape need to be constructed as the program runs objects need to be created and the constructor arguments are not known until run time CSC Data Structures/Algorithms29

Dynamic memory allocation Pointers need to be used for dynamic allocation of memory Use the operator new to dynamically allocate space Use the operator delete to later free this space CSC Data Structures/Algorithms30

The new operator If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. If sufficient memory is not available, the new operator returns NULL. The dynamically allocated object/array exists until the delete operator destroys it. CSC Data Structures/Algorithms31

The delete operator The delete operator deallocates the object or array currently pointed to by the pointer which was previously allocated at run-time by the new operator. the freed memory space is returned to Heap the pointer is then considered unassigned If the value of the pointer is NULL there is no effect. CSC Data Structures/Algorithms32

Example CSC Data Structures/Algorithms33 FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL;

CSC Data Structures/Algorithms34 Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; 0EC4 FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr

CSC Data Structures/Algorithms35 Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; 0EC4 22 FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr

CSC Data Structures/Algorithms36 Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; 0EC4 22 FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr Output: 22

CSC Data Structures/Algorithms37 Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; ? FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr

CSC Data Structures/Algorithms38 Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; 0 FDE1 FDE0 0EC7 FDE2 FDE3 0EC4 0EC5 0EC6 ptr

Dynamic allocation and deallocation of arrays Use the [IntExp] on the new statement to create an array of objects instead of a single instance. On the delete statement use [] to indicate that an array of objects is to be deallocated. CSC Data Structures/Algorithms39

Example of dynamic array allocation CSC Data Structures/Algorithms40 int* grades = NULL; int numberOfGrades; cout << "Enter the number of grades: "; cin >> numberOfGrades; grades = new int[numberOfGrades]; for (int i = 0; i < numberOfGrades; i++) cin >> grades[i]; for (int j = 0; j < numberOfGrades; j++) cout << grades[j] << " "; delete [] grades; grades = NULL;

Dynamic allocation of 2D arrays A two dimensional array is really an array of arrays (rows). To dynamically declare a two dimensional array of int type, you need to declare a pointer to a pointer as: int **matrix; CSC Data Structures/Algorithms41

Dynamic allocation of 2D arrays (Cont..) To allocate space for the 2D array with r rows and c columns: You first allocate the array of pointers which will point to the arrays (rows) matrix = new int*[r]; This creates space for r addresses; each being a pointer to an int. Then you need to allocate the space for the 1D arrays themselves, each with a size of c for(i=0; i<r; i++) matrix[i] = new int[c]; CSC Data Structures/Algorithms42

Dynamic allocation of 2D arrays (Cont..) The elements of the array matrix now can be accessed by the matrix[i][j] notation Keep in mind, the entire array is not in contiguous space (unlike a static 2D array) The elements of each row are in contiguous space, but the rows themselves are not. matrix[i][j+1] is after matrix[i][j] in memory, but matrix[i][0] may be before or after matrix[i+1][0] in memory CSC Data Structures/Algorithms43

Example // create a 2D array dynamically int rows, columns, i, j; int **matrix; cin >> rows >> columns; matrix = new int*[rows]; for(i=0; i<rows; i++) matrix[i] = new int[columns]; CSC Data Structures/Algorithms44 // deallocate the array for(i=0; i<rows; i++) delete [] matrix[i]; delete [] matrix;

CSC Data Structures/Algorithms45 Passing pointers to a function

Pointers as arguments to functions Pointers can be passed to functions just like other types. Just as with any other argument, verify that the number and type of arguments in function invocation match the prototype (and function header). CSC Data Structures/Algorithms46

Example of pointer arguments void Swap(int *p1, int *p2); void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(&x,&y); // passes addresses of x and y explicitly cout << x << " " << y << endl; } void Swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } CSC Data Structures/Algorithms47

Example of reference arguments void Swap(int &a, int &b); void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(x,y); // passes addresses of x and y implicitly cout << x << " " << y << endl; } void Swap(int &a, int &b) { int temp = a; a = b; b = temp; } CSC Data Structures/Algorithms48

More example CSC Data Structures/Algorithms49 void main () { int r, s = 5, t = 6; int *tp = &t; r = MyFunction(tp,s); r = MyFunction(&t,s); r = MyFunction(&s,*tp); } int MyFunction(int *p, int i) { *p = 3; i = 4; return i; }

CSC Data Structures/Algorithms50 Memory leaks and Dangling Pointers

Memory leaks When you dynamically create objects, you can access them through the pointer which is assigned by the new operator Reassigning a pointer without deleting the memory it pointed to previously is called a memory leak It results in loss of available memory space CSC Data Structures/Algorithms51

Memory leak example CSC Data Structures/Algorithms52 int *ptr1 = new int; int *ptr2 = new int; *ptr1 = 8; *ptr2 = 5; ptr1 8 5 ptr2 ptr1 8 5 ptr2 ptr2 = ptr1; How to avoid?

Inaccessible object An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it. It is a logical error and causes memory leaks. CSC Data Structures/Algorithms53

Dangling Pointer It is a pointer that points to dynamic memory that has been deallocated. The result of dereferencing a dangling pointer is unpredictable. CSC Data Structures/Algorithms54

CSC Data Structures/Algorithms55 Dangling Pointer example int *ptr1 = new int; int *ptr2; *ptr1 = 8; ptr2 = ptr1; ptr1 8 ptr2 delete ptr1; ptr1 ptr2 How to avoid?

Pointers to objects

Any type that can be used to declare a variable/object can also have a pointer type. Consider the following class: CSC Data Structures/Algorithms57 class Rational { private: int numerator; int denominator; public: Rational(int n, int d); void Display(); };

Pointers to objects (Cont..) CSC Data Structures/Algorithms58 Rational *rp = NULL; Rational r(3,4); rp = &r; 0 FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD rp

Pointers to objects (Cont..) CSC Data Structures/Algorithms59 Rational *rp = NULL; Rational r(3,4); rp = &r; 0 FFF0 numerator = 3 denominator = 4 FFF1 FFF2 FFF3 3 FFF4 FFF5 FFF6 FFF7 4 FFF8 FFF9 FFFA FFFB FFFC FFFD rp r

Pointers to objects (Cont..) CSC Data Structures/Algorithms60 Rational *rp = NULL; Rational r(3,4); rp = &r; FFF4 FFF0 numerator = 3 denominator = 4 FFF1 FFF2 FFF3 3 FFF4 FFF5 FFF6 FFF7 4 FFF8 FFF9 FFFA FFFB FFFC FFFD r rp

Pointers to objects (Cont..) If rp is a pointer to an object, then two notations can be used to reference the instance/object rp points to. Using the de-referencing operator * (*rp).Display(); Using the member access operator -> rp -> Display(); CSC Data Structures/Algorithms61

Dynamic Allocation of a Class Object Consider the Rational class defined before Rational *rp; int a, b; cin >> a >> b; rp = new Rational(a,b); (*rp).Display(); // rp->Display(); delete rp; rp = NULL; CSC Data Structures/Algorithms62