Pointers Typedef Pointer Arithmetic Pointers and Arrays.

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.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
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. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
 2006 Pearson Education, Inc. All rights reserved Pointers.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
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.
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: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
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.
Dynamic memory allocation and Pointers Lecture 4.
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.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
[S. Uludag] CIS / CSC 175 Problem Solving and Programming I Winter 2010 Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
C++ Pointers Read Chapter 2 (P ). COP3530 – C++ Pointers Pointers Pointers provide a method of referencing the memory location of variables provide.
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.
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.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Variables and memory addresses
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
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.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
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.
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.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Pointers and Dynamic Arrays
Pointers and Dynamic Arrays
Chapter 9: Pointers.
Lecture 6 C++ Programming
Pointers and Dynamic Variables
Pointers and Dynamic Variables
Pointers, Dynamic Data, and Reference Types
Computer Skills2 for Scientific Colleges
Presentation transcript:

Pointers Typedef Pointer Arithmetic Pointers and Arrays

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 C++.

Assume that we have declared an integer variable v1, and that the compiler has assigned the memory address of 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 and its name is V1. 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 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; int pointer

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

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

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 type!

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.

int x = 3; int* xPtr; void* yPtr; xPtr = &x; yPtr = xPtr; cout (yPtr) ); cout << *((int*)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.

In C++, you can assign a name to a type definition and than later use that name to declare variables. typedef int* IntPtr; IntPtr xPtr, yPtr; the typedef statement should be placed outside of any function so that it is global. later, when we declare xPtr and yPtr, the name IntPtr is an alias for int*. Thus, xPtr and yPtr are declared as int pointers. typedefs provide no additional function. They are strictly for style and readability.

Using a pointer as a call-by-value parameter can be troublesome. Consider the following example …

typedef int* IntPointer; void sneaky (IntPointer temp) { *temp = 99; cout << “Inside sneaky! *temp = “ << *temp << endl; } Since this is a pass by value, you might not expect any side effects.

int main ( ) { IntPointer p; p = new int; *p = 77; cout << “Before calling sneaky! *p = “ << *p << endl; sneaky ( p ); cout << “After calling sneaky! *p = “ << *p << endl; return 0; }

int main ( ) { IntPointer p; p = new int; *p = 77; cout << “Before calling sneaky! *p = “ << *p << endl; sneaky ( p ); cout << “After calling sneaky! *p = “ << *p << endl; return 0; } p 77

p void sneaky (IntPointer temp) { *temp = 99; cout << “Inside sneaky! *temp = “ << *temp << endl; } temp 99 77

int main ( ) { IntPointer p; p = new int; *p = 77; cout << “Before calling sneaky! *p = “ << *p << endl; sneaky ( p ); cout << “After calling sneaky! *p = “ << *p << endl; return 0; } p 99

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

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

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 arrithmetic is only legal 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. “If NOT you will be punished!!”

Recall that C-style character strings are just arrays of characters (terminated by a null). Therefore we can use pointer arithmetic to move through a C-style character string as shown … char * colorPtr = “blue”; … colorPtr++; …

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! Why?

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: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5;... } int main ( ) {... this is a global variable it is stored in the data segment. this is a local variable it is stored on the stack.

Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5;... } int main ( ) {... valueOne exists for the entire life of the program. valueTwo comes into existence when it is declared, and disappears when the function ends.

What if you want to control when a variable comes into existence, and when it goes away!

int* a = new int; CoinBank* myBank = new CoinBank(5,3); This is a pointer. This variable is stored on the heap. Storage from the heap is allocated dynamically as your program executes, These variable come into existence when they are declared.

Dynamically allocated variables will stay around until you explicitly delete them. Thus, they are completely under programmer control. To delete a dynamically allocated variable you would write delete a; where a was a pointer to the variable.

Recall that when we talked about arrays, we noted that the array size given in the array declaration had to be a constant value. That is, the array size had to be fixed at compile time. This presents some difficulties: * either we guess too low and the array is not big enough to hold all of the data required, or * we guess to high and we waste space because elements of the array are not used.

One approach to solving this problem is to allocate the storage required for the array at run-time. int size; cout << “How big is the array?”; cin >> size; int *myArray; myArray = new int [size]; since we are allocating storage at run-time, we are allowed to use a variable as the array size.

Now, remembering the relationship between an array name and a pointer, we can use the dynamic array just like a normal array… myArray [5] = 15; cout << myArray[n];

Whenever you use [ ] with new to allocate an array dynamically, you must use the corresponding form of the delete, delete [ ]. That is, if you write int *myArray; myArray = new int [10]; You must write delete [ ] myArray; to delete the array!

When we dynamically storage for an object or a struct, we no longer use the dot operator to access its data members. Instead we use the -> (pointer) operator. piggyBankPtr = new PiggyBank; piggyBankPtr->moneyInBank = 12.45;

Every object that you create has an implicit data member that carries the address of the object. This pointer is called the this pointer. The this pointer can be used by member functions that need the address of the calling object. void CoinBank::displayMoney( ) { cout moneyInBank; } note that we seldom use the this pointer this way. It is simpler to write cout << moneyInBank;

int *p; int *q; p = new int; q = p; *p = 46; *q = 39; delete p; cout << *p << “ “ << *q; p q variable name value in memory address

int *p; int *q; p = new int[5]; *p = 2; for (int j = 1; j < 5; j++) p[j] = j + 3; q = p; delete [] p; for (int j = 0; j < 5; j++) cout << q[j] << “ “; p q variable name value in memory address

Find the mistakes… int *p = new int; p = 5; *p = *p + 5; Employee e1 = new Employee(“Hacker”, “Harry”, 34000); Employee e2; e2->setSalary(38000); delete e2; Time *pnow = new Time( ); Time *t1 = new Time(2, 0, 0); delete *t1; cout getSeconds( );