chapter 9 pointers

21
Chapter 9 Pointers Chapter 9 Pointers Fall 2005 Fall 2005 Csc 125 Introduction to Csc 125 Introduction to C++ C++

Upload: hillary-goff

Post on 03-Jan-2016

117 views

Category:

Documents


7 download

DESCRIPTION

Chapter 9 Pointers. Fall 2005 Csc 125 Introduction to C++. Topics. Getting the Address of a Variable Pointer Variables The Relationship Between Arrays and Pointers Pointer Arithmetic Initializing Pointers. Topics. Comparing Pointers Pointers as Function Parameters - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 9 Pointers

Chapter 9 PointersChapter 9 Pointers

Fall 2005Fall 2005

Csc 125 Introduction to C++Csc 125 Introduction to C++

Page 2: Chapter 9 Pointers

TopicsTopics

• Getting the Address of a VariableGetting the Address of a Variable

• Pointer VariablesPointer Variables

• The Relationship Between Arrays and The Relationship Between Arrays and PointersPointers

• Pointer ArithmeticPointer Arithmetic

• Initializing PointersInitializing Pointers

Page 3: Chapter 9 Pointers

TopicsTopics

• Comparing PointersComparing Pointers

• Pointers as Function ParametersPointers as Function Parameters

• Dynamic Memory AllocationDynamic Memory Allocation

• Returning Pointers from FunctionsReturning Pointers from Functions

Page 4: Chapter 9 Pointers

Getting the Address of a Getting the Address of a VariableVariable

• Each variable in program is stored at Each variable in program is stored at a unique addressa unique address

• Use address operator Use address operator && to get to get address of a variable:address of a variable:int num = -23;int num = -23;

cout << &num; // prints addresscout << &num; // prints address

// in hexadecimal// in hexadecimal

Page 5: Chapter 9 Pointers

Pointer VariablesPointer Variables

• Pointer variablePointer variable ( (pointerpointer): variable ): variable that holds an addressthat holds an address

• Can perform some tasks more easily Can perform some tasks more easily with an address than by accessing with an address than by accessing memory via a symbolic name:memory via a symbolic name:– Accessing unnamed memory locationsAccessing unnamed memory locations– Array manipulationArray manipulation– etc.etc.

Page 6: Chapter 9 Pointers

Pointer VariablesPointer Variables

• Definition:Definition:int *intptr;int *intptr;

• Read as:Read as:

““intptrintptr can hold the address of an can hold the address of an int”int”

• Spacing in definition does not matter:Spacing in definition does not matter:int * intptr; // same as aboveint * intptr; // same as above

int* intptr; // same as aboveint* intptr; // same as above

Page 7: Chapter 9 Pointers

Pointer VariablesPointer Variables

• Assignment:Assignment:int *intptr;int *intptr;intptr = &num;intptr = &num;

• Memory layout:Memory layout:

• Can access Can access numnum using using intptrintptr and and indirection operatorindirection operator **::

cout << *intptr << endl; // prints 25 cout << *intptr << endl; // prints 25

num intptr25 0x4a00

address of num: 0x4a00

Page 8: Chapter 9 Pointers

The Relationship Between The Relationship Between Arrays and PointersArrays and Pointers

• Array name is starting address of arrayArray name is starting address of arrayint vals[] = {4, 7, 11};int vals[] = {4, 7, 11};

cout << vals;cout << vals; // displays // displays

// 0x4a00// 0x4a00

cout << vals[0]; // displays 4cout << vals[0]; // displays 4

44 77 1111starting address of vals: 0x4a00

Page 9: Chapter 9 Pointers

The Relationship Between The Relationship Between Arrays and PointersArrays and Pointers

• Array name can be used as a pointer Array name can be used as a pointer constant:constant:int vals[] = {4, 7, 11};int vals[] = {4, 7, 11};

cout << *vals; // displays 4cout << *vals; // displays 4

• Pointer can be used as an array Pointer can be used as an array name:name:int *valptr = vals;int *valptr = vals;

cout << valptr[1]; // displays 7cout << valptr[1]; // displays 7

Page 10: Chapter 9 Pointers

Pointers in ExpressionsPointers in Expressions

Given:Given:int vals[]={4,7,11}, *valptr;int vals[]={4,7,11}, *valptr;

valptr = vals;valptr = vals;

What is What is valptr + 1valptr + 1? ? It means It means (address in (address in valptrvalptr) + (1 * size of an ) + (1 * size of an int)int)cout << *(valptr+1); //displays 7cout << *(valptr+1); //displays 7cout << *(valptr+2); //displays 11cout << *(valptr+2); //displays 11

Must use Must use ( )( ) in expression in expression

Page 11: Chapter 9 Pointers

Array AccessArray Access

• Array elements can be accessed in many Array elements can be accessed in many ways:ways:Array access methodArray access method ExampleExample

array name and array name and [][] vals[2] = 17;vals[2] = 17;

pointer to array and pointer to array and [][]

valptr[2] = 17;valptr[2] = 17;

array name and array name and subscript arithmeticsubscript arithmetic

*(vals + 2) = 17;*(vals + 2) = 17;

pointer to array and pointer to array and subscript arithmeticsubscript arithmetic

*(valptr + 2) = 17;*(valptr + 2) = 17;

Page 12: Chapter 9 Pointers

Array AccessArray Access

• Conversion: Conversion: vals[i]vals[i] is equivalent is equivalent to to *(vals + i)*(vals + i)

• No bounds checking performed on No bounds checking performed on array access, whether using array array access, whether using array name or a pointername or a pointer

Page 13: Chapter 9 Pointers

Pointer ArithmeticPointer Arithmetic

• Operations on pointer variables:Operations on pointer variables:OperationOperation ExampleExample

int vals[]={4,7,11}; int vals[]={4,7,11}; int *valptr = vals;int *valptr = vals;

++, --++, -- valptr++; // points at 7valptr++; // points at 7valptr--; // now points at 4valptr--; // now points at 4

+, - +, - (pointer and (pointer and intint)) cout << *(valptr + 2); // 11cout << *(valptr + 2); // 11

+=, -= +=, -= (pointer (pointer and and intint))

valptr = vals; // points at 4valptr = vals; // points at 4valptr += 2; // points at 11valptr += 2; // points at 11

- - (pointer from (pointer from pointer)pointer)

cout << valptr–val; // differencecout << valptr–val; // difference//(number of ints) between valptr//(number of ints) between valptr// and val // and val

Page 14: Chapter 9 Pointers

Initializing PointersInitializing Pointers

• Can initialize at definition time:Can initialize at definition time:int num, *numptr = &num;int num, *numptr = &num;int val[3], *valptr = val;int val[3], *valptr = val;

• Cannot mix data types:Cannot mix data types:double cost;double cost;int *ptr = &cost; // won’t workint *ptr = &cost; // won’t work

• Can test for an invalid address for Can test for an invalid address for ptrptr with:with:if (!ptr) ...if (!ptr) ...

Page 15: Chapter 9 Pointers

Comparing PointersComparing Pointers

• Relational operators (Relational operators (<<, , >=>=, etc.) can be , etc.) can be used to compare addresses in pointersused to compare addresses in pointers

• Comparing addresses Comparing addresses inin pointers is not pointers is not the same as comparing contents the same as comparing contents pointed at bypointed at by pointers: pointers:if (ptr1 == ptr2) // comparesif (ptr1 == ptr2) // compares

// addresses// addressesif (*ptr1 == *ptr2) // comparesif (*ptr1 == *ptr2) // compares

// contents// contents

Page 16: Chapter 9 Pointers

Pointers as Function Pointers as Function ParametersParameters• A pointer can be parameterA pointer can be parameter• Works like reference variable to allow change to Works like reference variable to allow change to

argument from within functionargument from within function• Requires:Requires:

1)1) asterisk * on parameter in prototype and headingasterisk * on parameter in prototype and heading

void getNum(int *ptr); // ptr is pointer to an intvoid getNum(int *ptr); // ptr is pointer to an int 2)2) asterisk asterisk ** in body to dereference the pointerin body to dereference the pointer

cin >> *ptr;cin >> *ptr; 3)3) address as argument to the functionaddress as argument to the function

getNum(&num); // pass address of num to getNumgetNum(&num); // pass address of num to getNum

Page 17: Chapter 9 Pointers

Pointers as Function Pointers as Function ParametersParametersvoid swap(int *x, int *y)void swap(int *x, int *y){{ int temp;int temp;

temp = *x;temp = *x;*x = *y;*x = *y;*y = temp;*y = temp;

}}

int num1 = 2, num2 = -3;int num1 = 2, num2 = -3;swap(&num1, &num2);swap(&num1, &num2);

Page 18: Chapter 9 Pointers

Dynamic Memory AllocationDynamic Memory Allocation

• Can allocate storage for a variable Can allocate storage for a variable while program is runningwhile program is running

• Computer returns address of newly Computer returns address of newly allocated variableallocated variable

• Uses Uses newnew operator to allocate memory: operator to allocate memory:double *dptr;double *dptr;dptr = new double;dptr = new double;

•newnew returns address of memory returns address of memory locationlocation

Page 19: Chapter 9 Pointers

Dynamic Memory Dynamic Memory AllocationAllocation• Can also use Can also use newnew to allocate array: to allocate array:const int SIZE = 25;const int SIZE = 25;arrayPtr = new double[SIZE];arrayPtr = new double[SIZE];

• Can then use Can then use [][] or pointer arithmetic to or pointer arithmetic to access array:access array:

for(i = 0; i < SIZE; i++)for(i = 0; i < SIZE; i++) arrayptr[i] = i * i;arrayptr[i] = i * i;

ororfor(i = 0; i < SIZE; i++)for(i = 0; i < SIZE; i++)

*(arrayptr + i) = i * i;*(arrayptr + i) = i * i;

• Program will terminate if not enough Program will terminate if not enough memory available to allocatememory available to allocate

Page 20: Chapter 9 Pointers

Releasing Dynamic MemoryReleasing Dynamic Memory

• Use Use deletedelete to free dynamic memory: to free dynamic memory:delete fptr;delete fptr;

• Use Use [][] to free dynamic array: to free dynamic array:delete [] arrayptr;delete [] arrayptr;

• Only use Only use deletedelete with dynamic with dynamic memory! memory!

Page 21: Chapter 9 Pointers

Returning Pointers from Returning Pointers from FunctionsFunctions• Pointer can be return type of function:Pointer can be return type of function:

int* newNum();int* newNum();

• Function must not return a pointer to Function must not return a pointer to a local variable in the functiona local variable in the function

• Function should only return a pointer:Function should only return a pointer:– to data that was passed to the function to data that was passed to the function

as an argumentas an argument– to dynamically allocated memoryto dynamically allocated memory