 2006 Pearson Education, Inc. All rights reserved. 1 8 8 Pointers.

Slides:



Advertisements
Similar presentations
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
CS 141 Computer Programming 1 1 Pointers. Pointer Variable Declarations and Initialization Pointer variables –Contain memory addresses as values –Normally,
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
 2006 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
 2000 Deitel & Associates, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Review of C++ Programming Part II Sheng-Fang Huang.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 8 Pointers C++ How to Program, 9/e
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
(continue) © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
[S. Uludag] CIS / CSC 175 Problem Solving and Programming I Winter 2010 Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5: Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization.
 2007 Pearson Education, Inc. All rights reserved. 1 C Pointers Chapter 7 from “C How to Program" Another ref:
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Pointers Class #9 – Pointers Pointers Pointers are among C++ ’ s most powerful, yet most difficult concepts to master. We ’ ve seen how we can use references.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
1 Lecture 12 Pointers and Strings Section 5.4, ,
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization 5.3Pointer Operators 5.4Calling Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2006 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
EC-111 Algorithms & Computing Lecture #9 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Week 9 - Pointers.
Chapter 7 - Pointers Outline 7.1 Introduction
POINTERS.
Chapter 7 - Pointers Outline 7.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Pointers and Pointer-Based Strings
8 Pointers.
Pointers and Pointer-Based Strings
Chapter 7 from “C How to Program"
Pointers and Pointer-Based Strings
Pointers Kingdom of Saudi Arabia
5.1 Introduction Pointers Powerful, but difficult to master
7 C Pointers.
Pointers and Pointer-Based Strings
EENG212 ALGORITHMS & DATA STRUCTURES
C++ Programming Lecture 17 Pointers – Part I
POINTERS.
Lecture 2 Arrays & Pointers May 17, 2004
Lecture 2 Arrays & Pointers September 7, 2004
CISC181 Introduction to Computer Science Dr
Presentation transcript:

 2006 Pearson Education, Inc. All rights reserved Pointers

 2006 Pearson Education, Inc. All rights reserved Introduction 8.2 Pointer Variable Declarations and Initialization 8.3 Pointer Operators 8.4 Passing Arguments to Functions by Reference with Pointers 8.5 Using const with Pointers 8.6 Selection Sort Using Pass-by-Reference 8.7 sizeof Operators 8.7 Pointer Expressions and Pointer Arithmetic 8.9 Relationship Between Pointers and Arrays 8.10 Arrays of Pointers 8.11 Case Study: Card Shuffling and Dealing Simulation 8.12 Function Pointers 8.13 Introduction to Pointer-Based String Processing Fundamentals of Characters and Pointer-Based Strings String Manipulation Functions of the String-Handling Library 8.14 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved Introduction Pointers – Powerful, but difficult to master – Can be used to perform pass-by-reference – Can be used to create and manipulate dynamic data structures

 2006 Pearson Education, Inc. All rights reserved Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as values Normally, variable contains specific value (direct reference) Pointers contain address of variable that has specific value (indirect reference) Indirection – Referencing value through pointer

 2006 Pearson Education, Inc. All rights reserved. 5 Fig. 8.1 | Directly and indirectly referencing a variable.

 2006 Pearson Education, Inc. All rights reserved Pointer Variable Declarations and Initialization (Cont.) Pointer declarations – * indicates variable is a pointer Example – int *myPtr; Declares pointer to int, of type int * Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; Pointer initialization – Initialized to 0, NULL, or an address 0 or NULL points to nothing (null pointer) – Initialize pointers to prevent pointing to unknown or uninitialized areas of memory.

 2006 Pearson Education, Inc. All rights reserved Pointer Operators Address operator ( & ) – Returns memory address of its operand – Example int y = 5; int *yPtr; yPtr = &y; assigns the address of variable y to pointer variable yPtr – Variable yPtr “points to” y yPtr indirectly references variable y ’s value

 2006 Pearson Education, Inc. All rights reserved. 8 Fig. 8.3 | Representation of y and yPtr in memory.

 2006 Pearson Education, Inc. All rights reserved Pointer Operators (Cont.) * operator – Also called indirection operator or dereferencing operator – Returns synonym for the object its operand points to – *yPtr returns y (because yPtr points to y ) – Dereferenced pointer is an lvalue *yptr = 9; * and & are inverses of each other – Will “cancel one another out” when applied consecutively in either order

 2006 Pearson Education, Inc. All rights reserved. 10 Common Programming Error 8.2 Dereferencing a pointer that has not been properly initialized or that has not been assigned to point to a specific location in memory could cause a fatal execution-time error, or it could accidentally modify important data and allow the program to run to completion, possibly with incorrect results.

 2006 Pearson Education, Inc. All rights reserved. 11 Outline fig08_04.cpp

 2006 Pearson Education, Inc. All rights reserved. 12 Fig. 8.5 | Operator precedence and associativity.

 2006 Pearson Education, Inc. All rights reserved Passing Arguments to Functions by Reference with Pointers Passing pointer arguments – Simulates pass-by-reference Use pointers and indirection operator – Pass address of argument using & operator – Arrays not passed with & because array name is already a pointer – * operator used as alias/nickname for variable inside of function

 2006 Pearson Education, Inc. All rights reserved. 14 Outline fig08_07.cpp (1 of 1)

 2006 Pearson Education, Inc. All rights reserved Using const with Pointers const qualifier – Indicates that value of variable should not be modified – const used when function does not need to change the variable’s value Principle of least privilege – Award function enough access to accomplish task, but no more – Example A function that prints the elements of an array, takes array and int indicating length – Array contents are not changed – should be const – Array length is not changed – should be const

 2006 Pearson Education, Inc. All rights reserved Using const with Pointers (Cont.) Nonconstant pointer to nonconstant data – Data can be modified through the dereferenced pointer – Pointer can be modified to point to other data Nonconstant pointer to constant data – Pointer can be modified to point to any appropriate data item – Data cannot be modified through this pointer Constant pointer to nonconstant data – Always points to the same memory location Can only access other elements using subscript notation – Must be initialized when declared – Data can be modified through the pointer – Default for an array name

 2006 Pearson Education, Inc. All rights reserved sizeof Operators sizeof operator – Returns size of operand in bytes – Can be used with Variable names Type names Constant values – The number of bytes used to store a particular data type may vary between systems.

 2006 Pearson Education, Inc. All rights reserved Pointer Expressions and Pointer Arithmetic Pointer arithmetic – Increment/decrement pointer ( ++ or -- ) – Add/subtract an integer to/from a pointer ( + or +=, - or -= ) – Pointers may be subtracted from each other – Pointer arithmetic is meaningless unless performed on a pointer to an array

 2006 Pearson Education, Inc. All rights reserved Pointer Expressions and Pointer Arithmetic (Cont.) 5 element int array on a machine using 4 byte int s – vPtr points to first element v[ 0 ], at location 3000 vPtr = &v[ 0 ]; – vPtr += 2; sets vPtr to 3008 ( * 4 ) vPtr points to v[ 2 ] Subtracting pointers – Returns number of elements between two addresses vPtr2 = &v[ 2 ]; vPtr = &v[ 0 ]; vPtr2 - vPtr is 2

 2006 Pearson Education, Inc. All rights reserved. 20 Fig | Pointer vPtr before and after pointer arithmetic.

 2006 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 8.9 Using pointer arithmetic on a pointer that does not refer to an array of values is a logic error.

 2006 Pearson Education, Inc. All rights reserved Pointer Expressions and Pointer Arithmetic (Cont.) Pointer assignment – Pointer can be assigned to another pointer if both are of same type If not same type, cast operator must be used Exception – Pointer to void (type void * ) Generic pointer, represents any type No casting needed to convert pointer to void * Casting is needed to convert void * to any other type void pointers cannot be dereferenced

 2006 Pearson Education, Inc. All rights reserved Pointer Expressions and Pointer Arithmetic (Cont.) Pointer comparison – Use equality and relational operators – Compare addresses stored in pointers Comparisons are meaningless unless pointers point to members of the same array – Commonly used to determine whether pointer is 0 (null pointer)

 2006 Pearson Education, Inc. All rights reserved Relationship Between Pointers and Arrays Arrays and pointers are closely related – Array name is like constant pointer – Pointers can do array subscripting operations Although array names are pointers to the beginning of the array, array names cannot be modified in arithmetic expressions, because array names are constant pointers.

 2006 Pearson Education, Inc. All rights reserved Relationship Between Pointers and Arrays (Cont.) Accessing array elements with pointers – Assume declarations: int b[ 5 ]; int *bPtr; bPtr = b; – Element b[ n ] can be accessed by *( bPtr + n ) Called pointer/offset notation – Addresses &b[ 3 ] is same as bPtr + 3 – Array name can be treated as pointer b[ 3 ] is same as *( b + 3 ) – Pointers can be subscripted (pointer/subscript notation) bPtr[ 3 ] is same as b[ 3 ]

 2006 Pearson Education, Inc. All rights reserved. 26 Dynamic Memory Management: Dynamic memory management – Enables programmers to allocate and deallocate memory for any built-in or user-defined type – Performed by operators new and delete – For example, dynamically allocating memory for an array instead of using a fixed-size array

 2006 Pearson Education, Inc. All rights reserved. 27 Dynamic Memory Management Operator new – Allocates (i.e., reserves) storage of the proper size for an object at execution time – Calls a constructor to initialize the object – Returns a pointer of the type specified to the right of new – Can be used to dynamically allocate any fundamental type (such as int or double ) or any class type Free store – Sometimes called the heap – Region of memory assigned to each program for storing objects created at execution time

 2006 Pearson Education, Inc. All rights reserved. 28 Dynamic Memory Management Operator delete – Destroys a dynamically allocated object – Calls the destructor for the object – Deallocates (i.e., releases) memory from the free store – The memory can then be reused by the system to allocate other objects Not releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely. This is sometimes called a “memory leak.”

 2006 Pearson Education, Inc. All rights reserved. 29 Dynamic Memory Management new operator can be used to allocate arrays dynamically – Dynamically allocate a 10-element integer array: int *gradesArray = new int[ 10 ]; – Size of a dynamically allocated array Specified using any integral expression that can be evaluated at execution time

 2006 Pearson Education, Inc. All rights reserved. 30 Dynamic Memory Management Delete a dynamically allocated array: delete [] gradesArray; – This deallocates the array to which gradesArray points – If the pointer points to an array of objects First calls the destructor for every object in the array Then deallocates the memory – If the statement did not include the square brackets ( [] ) and gradesArray pointed to an array of objects Only the first object in the array would have a destructor call

 2006 Pearson Education, Inc. All rights reserved. 31 Dynamic 1-D arrays int *grades, no, i; cout << “No of students: "; cin >> no; grades = new int[no]; for (i = 0; i < no; i++){ cout << "Enter the grade: "; cin >> grades[i]; } for (i = 0; i < no; i++) cout << grades[i] << endl; delete []grades; Write a code segment that takes the grades of students from the user and displays them on the screen. Your code should work for different class sizes specified by the user.

 2006 Pearson Education, Inc. All rights reserved. 32 Dynamic 2-D arrays (pointers of pointers) float **grades; int *examNo, studentNo, i, j; cout << "No of students: "; cin >> studentNo; grades = new float *[studentNo]; examNo = new int [studentNo]; for (i = 0; i < studentNo; i++){ cout << "No of exams for " << i; cin >> examNo[i]; grades[i] = new float[examNo[i]]; for (j = 0; j < examNo[i]; j++) grades[i][j] = 0; } for (i = 0; i < studentNo; i++) delete [] grades[i]; delete [] grades; delete [] examNo; Write a code segment that initializes the grades of students each of which takes different number of exams. Your code should work for different class sizes specified by the user.

 2006 Pearson Education, Inc. All rights reserved. 33 Dynamic 2-D arrays (array of pointers) const int size = 6; int *triangle[size], i, j; for (i = 0; i < size; i++){ triangle[i] = new int[i+1]; for (j = 0; j < i+1; j++) triangle[i][j] = i+1; } for (i = 0; i < size; i++){ for (j = 0; j < i+1; j++) cout << triangle[i][j]; cout << endl; } for (i = 0; i < size; i++) delete [] triangle[i]; Write a code segment that draws acute triangles using digits. Each line should be filled with its corresponding line number. The height of the triangle is specified as 6. In other words, your code should draw the following figure on the screen

 2006 Pearson Education, Inc. All rights reserved. 34 Dynamic 2-D arrays (pointers of array) double (*points)[2]; int i, j, pointNo; cout << "Number of points: "; cin >> pointNo; points = new (double[pointNo])[2]; for (i = 0; i < pointNo; i++){ cout << "Enter x coordinate: "; cin >> points[i][0]; cout << "Enter y coordinate: "; cin >> points[i][1]; } for (i = 0; i < pointNo; i++){ cout << "x: " << points[i][0]; cout << ", y: " << points[i][1] << endl; } delete []points; Write a code segment that takes the coordinates of points (in a 2-D space) from the user and displays them on the screen. The number of the points is not known at the beginning of the program and the user will specify it.

 2006 Pearson Education, Inc. All rights reserved. 35 Dynamic 1-D arrays int takeGrade1(int *grades){ int i, noStudents; cout << "No of students: "; cin >> noStudents; grades = new int[noStudents]; for (i = 0; i < noStudents; i++){ cout << "Enter the grade: "; cin >> grades[i]; } return noStudents; } int main(){ int *studentGrades, no, i; no = takeGrade1(studentGrades); cout << endl << "Grades: " << endl; for (i = 0; i < no; i++) cout << studentGrades[i] << endl; delete []studentGrades; return 0; } Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. This program does not work correctly, WHY ?

 2006 Pearson Education, Inc. All rights reserved. 36 Dynamic 1-D arrays Output of the program: No of students: 3 Enter the grade: 89 Enter the grade: 56 Enter the grade: 76 Grades: Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. This program does not work correctly, WHY ?

 2006 Pearson Education, Inc. All rights reserved. 37 Dynamic 1-D arrays int *takeGrade2(int *noStudents){ int i, *grades; cout << "No of students: "; cin >> *noStudents; grades = new int[*noStudents]; for (i = 0; i < *noStudents; i++){ cout << "Enter the grade: "; cin >> grades[i]; } return grades; } int main(){ int *studentGrades, no, i; studentGrades = takeGrade2(&no); cout << endl << "Grades: " << endl; for (i = 0; i < no; i++) cout << studentGrades[i] << endl; delete []studentGrades; return 0; } Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. Passing the number of students to our function by reference with pointers and returning “grades” array

 2006 Pearson Education, Inc. All rights reserved. 38 Dynamic 1-D arrays Output of the program: No of students: 3 Enter the grade: 89 Enter the grade: 56 Enter the grade: 76 Grades: Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. Passing the number of students to our function by reference with pointers and returning “grades” array

 2006 Pearson Education, Inc. All rights reserved. 39 Dynamic 1-D arrays int takeGrade3(int **grades){ int i, noStudents; cout << "No of students: "; cin >> noStudents; *grades = new int[noStudents]; for (i = 0; i < noStudents; i++){ cout << "Enter the grade: "; cin >> (*grades)[i]; } return noStudents; } int main(){ int *studentGrades, no, i; no = takeGrade3(&studentGrades); cout << endl << "Grades: " << endl; for (i = 0; i < no; i++) cout << studentGrades[i] << endl; delete []studentGrades; return 0; } Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. Passing “grades” array to our function by reference with pointers and returning the number of students

 2006 Pearson Education, Inc. All rights reserved. 40 Dynamic 1-D arrays Output of the program: No of students: 3 Enter the grade: 89 Enter the grade: 56 Enter the grade: 76 Grades: Write a function that takes the grades of students from the user; this function should work for different class sizes specified by the user. Display the grades on the screen after calling this function. This time, you HAVE TO WRITE A FUNCTION which should return both the contents of the array and its size. Passing “grades” array to our function by reference with pointers and returning the number of students

 2006 Pearson Education, Inc. All rights reserved Case Study: Card Shuffling and Dealing Simulation Using array of strings (string array) – Array does not store strings, only pointers to strings Example – const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; Each element of suit points to a char * (string) "Hearts", "Diamonds", "Clubs", and "Spades" are somewhere in memory suit array has fixed size ( 4 ), but strings can be of any size Commonly used with command-line arguments to function main

 2006 Pearson Education, Inc. All rights reserved. 42 Fig | Graphical representation of the suit array.

 2006 Pearson Education, Inc. All rights reserved String Manipulation Functions of the String-Handling Library String handling library provides functions to – Manipulate string data – Compare strings – Search strings for characters and other strings – Tokenize strings (separate strings into logical pieces)

 2006 Pearson Education, Inc. All rights reserved. 44 Fig | String-manipulation functions of the string-handling library. (Part 1 of 2)

 2006 Pearson Education, Inc. All rights reserved. 45 Fig | String-manipulation functions of the string-handling library. (Part 2 of 2)