Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.

Slides:



Advertisements
Similar presentations
UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference
Advertisements

1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Pointer What it is How to declare it How to use it Relationship between arrays and pointers Relationship between strings and pointers.
Thursday, January 11, 2007 Harrisberger's Fourth Law of the Lab: Experience is directly proportional to the amount of equipment ruined Harrisberger's Fourth.
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: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
Computer Skills2 for Scientific Colleges 1 Pointers in C++ Topics to cover: Overview of Pointers Pointer Declaration Pointer Assignment 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: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
(continue) © by Pearson Education, Inc. All Rights Reserved.
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 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)
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Variables and memory addresses
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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Pointers  * symbol and & symbol  Pointer operations  Pointer.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Computer Skills2 for Scientific Colleges
Chapter 7 - Pointers Outline 7.1 Introduction
Chapter 7 - Pointers Outline 7.1 Introduction
Pointers and Pointer-Based Strings
CSC113: Computer Programming (Theory = 03, Lab = 01)
Lecture 6 C++ Programming
Programming fundamentals 2 Chapter 2:Pointer
Pointers and Dynamic Variables
Pointers, Dynamic Data, and Reference Types
Pointers and Pointer-Based Strings
Computer Skills2 for Scientific Colleges
Pointers Kingdom of Saudi Arabia
5.1 Introduction Pointers Powerful, but difficult to master
C++ Pointers and Strings
Pointers and Pointer-Based Strings
CISC181 Introduction to Computer Science Dr
C++ Pointers and Strings
Programming fundamentals 2 Chapter 3:Pointer
Presentation transcript:

Pointers

Topics Pointers Pointer Arithmetic Pointers and Arrays

Objectives on completion of this topic, students should be able to: Correctly use pointers in a C++ program * Take the address of a variable * Dereference a pointer * Do pointer arithmetic Explain the relationship between an array and a pointer * Use pointers to access array elements

Pointers are one of the most powerful but most difficult concepts to master in programming. Languages like C# don’t use pointers, except under special conditions, because they are so difficult.

Assume that we have declared an integer variable v1, and that the compiler has assigned the memory location for that integer value if integer variables take up 4 bytes of memory on this computer, then the address of the first byte of the integer is v1 is the name of the variable. We can access the variable by simply using its name. v1 = 34;

The address of the variable is We can store the address of a variable in a special data type called a pointer.

int v1; int *v1Ptr; v1Ptr = &v1 ; this statement declares the integer variable v1. Let us assume that the address of v1 in memory is this statement stores the address of the variable v1 in the variable v1Ptr. The & is called the address-of operator. this statement declares v1Ptr to be a variable of type integer pointer. That is, v1Ptr can contain a pointer to (the address of) an integer. Note that pointers are typed. This pointer points to an integer. To declare a pointer variable, place an asterisk in front of the variable name.

v v1Ptr v1Ptr is said to point to v1.

int v1; int *v1Ptr; v1Ptr = &v1; *v1Ptr = 45; cout << v1; the asterisk used as shown here is called the de-referencing operator. This statement says store the value 45 in the variable pointed to by v1Ptr.

v v1Ptr

Be careful when declaring pointers! int *aptr, bptr; aptr is a pointer but bptr is an int!

you must declare them this way! int *aptr, *bptr;

Null Pointers There is a special value “nullptr” that is used to indicate that a pointer does not point to anything. When first declaring a pointer, it is a good idea to set its value to nullptr, like this: int* intPtr = nullptr; You cannot dereference a null pointer. You should always test a pointer before you use it, to make sure it is not a NULL pointer: if (intPtr != nullptr)...

Pointer Assignment int v1, v2; int *v1Ptr, *v2Ptr; v1Ptr = &v1; *v1Ptr = 45; v2Ptr = v1Ptr; *v2Ptr = *v1Ptr; v1 v v1Ptr v2Ptr

Some Other Examples char *pc;// a pointer to a character char **pc;// a pointer to a pointer to a character char *pc[10];// an array of pointers to characters

void Pointer Recall that pointers are typed. int x = 3; int *xPtr; float *yPtr; xPtr = &x; yPtr = xPtr; this assignment won’t work because the pointer types are not the same!

The void pointer is a generic pointer type. That is, it can hold the address of any data type. So, we could use a void pointer to write int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr; Now this statement will compile and execute with no errors because yPtr is a generic pointer.

int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr; cout << *yPtr; However, this statement will not work. Because a void pointer is generic, it does not keep track of what kind of data it points to. Therefore, the computer cannot do the conversion necessary to print out the data pointed to by the void pointer.

Casting int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr; cout (yPtr) ); If we know what the data type is that the pointer points to, we can cast the pointer to the correct type to make the statement work. The type we are casting to, in this case an int* appears in parenthesis in front of the variable name.

Pointers and Arrays The name of an array is really a const pointer to the first element in the array! int myArray [4]; * myArray is an integer pointer. * myArray is a const pointer ( so that the address of myArray is not accidentally lost!) * myArray can be assigned to a pointer variable. myArray

Array/Pointer Duality Law a[n] is identical to *(a + n) where a is a pointer to an array and n is an integer offset.

#include using namespace std; int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << endl; return 0; } what will this statement display?

#include using namespace std; int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << “\n*intArray = “ << *intArray; cout << endl; return 0; } what will this statement display?

Pointer Arithmetic Since a pointer is just a normal variable we can do arithmetic on it like we can for any other variable. For example int *myPtr; myPtr++;// increment the pointer myPtr--;// decrement the pointer myPtr += 4;// add four to myPtr

int x[2]; int *aPtr; aPtr = x; *aPtr = 5; aPtr++; *aPtr = 8; X[0] X[1] aPtr address Note: When we increment a pointer, we increment it by the size of the data type it points to! Note however, that in C++, pointer arithmetic is only meaningful within an array.

Note the following interesting use of pointers and arrays. int myArray [4]; int* arrayPtr; arrayPtr = myArray; myArray [3] = 125; *(arrayPtr + 3) = 125; *(myArray + 3) = 125; arrayPtr [3] = 125; the assignment works because myArray is an int pointer. use pointer arithmetic to move the pointer to the 4 th element in the array (3 times size of int) aha … you can also use pointer arithmetic on the array name. and index notation on the pointer. these are all equivalent.

Great care should be taken when using pointer arithmetic to be sure that the pointer always points to valid data.

Pointers and C-Strings Recall that a C-style character string is just an array of characters that is null terminated. H e l l o W o r l d ‘\0’ char msg[ ] = “Hello World”;

Pointers and C-Strings The name of the array is a constant pointer to the first character in the array. H e l l o W o r l d ‘\0’ char msg[ ] = “Hello World”; msg

Functions that Return Arrays A function cannot return an entire array, that is, the following is illegal: int [ ] someFunction ( ); To create a function that achieves the desired result, write the function so that it returns a pointer of the base type of the array, for example: int* someFunction ( ); Warning: don’t return a pointer to data declared locally inside of the function!

The -> Operator We normally use the dot operator to reference member data or Member functions in an object. For example myCircle.getArea( ); But if we have a pointer to the object we have to use the -> operator, like this myCirclePtr->getArea( );

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

The implicit parameter When you send a message to an object, for example myCircle.getArea( ); The object that you send the message to is called the implicit parameter of the message. So, the this pointer points to the implicit parameter (i.e. the object You are sending the message to).

The implicit parameter 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.

Practice….

int x; int y; int *p = &x; int *q = &y; *p = 35; *q = 98; x y p q variable name value in memory address

int x; int y; int *p = &x; int *q = &y; x = 35; y = 46; p = q; *p = 78; x y p q variable name value in memory address

Given the definitions double values[ ] = {2, 3, 5, 17, 13}; double *p = values + 3; Explain the meaning of: values[1] values + 1 *(values + 1) p[1] p + 1 p - values

Suppose that you had the char array T h i s i s g o o d. if you had a pointer, cPtr, that pointed here and you put a null terminating character here then the statement cout << cPtr; would display the word is

Review of functions to manipulate char arrays strcat(char *str1, char *str2); strcmp(char *str1, char *str2); strcpy(char *str1, char *str2); strlen(char *str);

Common Pointer Errors Trying to dereference a NULL or uninitialized pointer Confusing pointers with the data to which they point Returning a pointer to data declared locally in a function

Pointers to Functions

Suppose that you wanted to display a table of values like this: … xf(x) = x 2

You could write this function: void printTable( ) { for (int x = 0; x < 10; x++) { int y = x * x; cout << x << ‘\t’ << y << endl; }

But suppose that you also wanted to output a table of x and f(x) = x - 1? or … x and f(x) = x or …

Function Pointers In C++ it is possible to pass the address of a function as a parameter to another function. The prototype for such a function looks like this: void doSomething( int (*f)(int) ); This is a pointer to a function * The function takes an integer parameter * The function returns an integer

Let’s write a function to compute the square of an integer: int square(int n) { return n * n; }

… and write the function to print a table like this: void printTable(int (*f)(int) ) { cout << setprecision(2); for (int x = 1; x < 10; x++) { int y = f(x); cout << x << '\t' << y << endl; } pointer to a function call the function f

To pass this function as a parameter to the printTable function, we simply pass the function’s name like this: printTable (square);

The power in this approach is that the printTable function can now print a table of the integers 1 through 10 and some value that is computed on each of those integers. But … the printTable function doesn’t know what calculation it is going to do. That knowledge is passed to printTable as a pointer to the function that actually does the calculation – in this case, the square function.