+ All Categories
Home > Documents > Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic...

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic...

Date post: 21-Dec-2015
Category:
View: 214 times
Download: 2 times
Share this document with a friend
Popular Tags:
46
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Chapter 9 Pointers and Dynamic Pointers and Dynamic Arrays Arrays
Transcript
Page 1: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 9Chapter 9Pointers and Dynamic Pointers and Dynamic

ArraysArrays

Page 2: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 2

OverviewOverview

9.1 Pointers9.1 Pointers

9.2 Dynamic Arrays9.2 Dynamic Arrays

Page 3: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

9.19.1PointersPointers

Page 4: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 4

PointersPointersA A pointer pointer is the memory address of a is the memory address of a variable variable

Memory addresses can be used as names Memory addresses can be used as names for variables for variables If a variable is stored in three memory If a variable is stored in three memory

locations, the address of the first can be locations, the address of the first can be used as a name for the variable. used as a name for the variable.

When a variable is used as a call-by-When a variable is used as a call-by-reference argument, its address is reference argument, its address is passed passed

Page 5: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 5

Pointers Tell Where To Find A VariablePointers Tell Where To Find A VariableAn address used to tell where a variable is An address used to tell where a variable is stored in memory is a stored in memory is a pointerpointer Pointers "point" to a variable by telling where Pointers "point" to a variable by telling where

the variable is locatedthe variable is located

Pointer variables must be declared to have a Pointer variables must be declared to have a pointer typepointer type Example: To declare a pointer variable p that Example: To declare a pointer variable p that

can "point" to a variable of type double:can "point" to a variable of type double: double *p;double *p;

The The asterisk identifies p as a pointer variableasterisk identifies p as a pointer variable

Page 6: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 6

Multiple Pointer DeclarationsMultiple Pointer Declarations

To declare multiple pointers in a statement, To declare multiple pointers in a statement, use the asterisk before each pointer use the asterisk before each pointer variablevariable Example: Example:

int *p1, *p2, v1, v2; int *p1, *p2, v1, v2;

p1 and p2 point to variables of type intp1 and p2 point to variables of type intv1 and v2 are variables of type intv1 and v2 are variables of type int

Page 7: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 7

The address of OperatorThe address of Operator

The The & operator& operator can be used to determine the can be used to determine the address of a variable which can be assigned to address of a variable which can be assigned to a pointer variablea pointer variable Example: p1 = &v1;Example: p1 = &v1;

p1 is now a pointer to v1 p1 is now a pointer to v1 v1 can be called v1 or "the variable v1 can be called v1 or "the variable

pointed to by p1"pointed to by p1"

Page 8: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 8

The Dereferencing OperatorThe Dereferencing Operator

C++ uses the * operator in yet another way C++ uses the * operator in yet another way with pointerswith pointers The phrase "The variable pointed to by The phrase "The variable pointed to by

p" is translated into C++ as *pp" is translated into C++ as *p Here the Here the * is the dereferencing operator* is the dereferencing operator

p is said to be p is said to be dereferenceddereferenced

Page 9: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 9

v1 and *p1 now refer to the same variable

A Pointer ExampleA Pointer Example

v1 = 0;v1 = 0;p1 = &v1;p1 = &v1;*p1 = 42;*p1 = 42;cout << v1 << endl;cout << v1 << endl;cout << *p1 << endl;cout << *p1 << endl;

output:output: 42 42 42 42

Page 10: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 10

Pointer AssignmentPointer Assignment

The assignment operator = is used to The assignment operator = is used to assign the value of one pointer to anotherassign the value of one pointer to another Example: Example: If p1 still points to v1 (previous slide) If p1 still points to v1 (previous slide)

thenthen p2 = p1; p2 = p1;causes *p2, *p1, and v1 all to name the causes *p2, *p1, and v1 all to name the same variablesame variable

Page 11: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Some care is required making assignments to Some care is required making assignments to pointer variablespointer variables p1= p3; // changes the location that p1 p1= p3; // changes the location that p1

"points" to"points" to

*p1 = *p3; // changes the value at the location *p1 = *p3; // changes the value at the location thatthat // p1 "points" to // p1 "points" to

Slide 9- 11

Caution! Pointer AssignmentsCaution! Pointer Assignments

Page 12: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 13: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 13

The new OperatorThe new Operator

Using pointers, variables can be manipulated Using pointers, variables can be manipulated even if there is no identifier for themeven if there is no identifier for them To create a pointer to a new "nameless" variable To create a pointer to a new "nameless" variable

of type int:of type int: p1 = new int; p1 = new int;

The new variable is referred to as *p1 The new variable is referred to as *p1 *p1 can be used anyplace an integer variable can*p1 can be used anyplace an integer variable can

cin >> *p1; cin >> *p1; *p1 = *p1 + 7; *p1 = *p1 + 7;

Page 14: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Variables created using the new operator Variables created using the new operator are called dynamic variablesare called dynamic variables Dynamic variables are created and Dynamic variables are created and

destroyed while the program is runningdestroyed while the program is running Additional examples of pointers and Additional examples of pointers and

dynamic variables are shown in the next dynamic variables are shown in the next slide.slide.

An illustration of the code is seen in the An illustration of the code is seen in the next slide. next slide.

Slide 9- 14

Dynamic VariablesDynamic Variables

Page 15: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 16: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 16

new and Class Typesnew and Class TypesUsing operator new with class types callsUsing operator new with class types callsa constructor as well as allocating memorya constructor as well as allocating memory If MyType is a class type, then If MyType is a class type, then

MyType *myPtr; // creates a pointer to a MyType *myPtr; // creates a pointer to a // variable of type MyType // variable of type MyType

myPtr = new MyType; myPtr = new MyType; // calls the default constructor // calls the default constructor

myPtr = new MyType (32.0, 17);myPtr = new MyType (32.0, 17); // calls Mytype(double, int); // calls Mytype(double, int);

Page 17: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 17

Basic Memory ManagementBasic Memory ManagementAn area of memory called the An area of memory called the freestorefreestore is isreserved for dynamic variablesreserved for dynamic variables New dynamic variables use memory in New dynamic variables use memory in

the freestorethe freestore If all of the freestore is used, calls to new If all of the freestore is used, calls to new

will failwill fail

Unneeded memory can be recycledUnneeded memory can be recycled When variables are no longer needed, When variables are no longer needed,

they can be deleted and the memory they can be deleted and the memory they used is returned to the freestorethey used is returned to the freestore

Page 18: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 18

The delete OperatorThe delete Operator

When dynamic variables are no longer When dynamic variables are no longer needed, delete them to return memory to needed, delete them to return memory to the freestorethe freestore Example: Example:

delete p;delete p;The value of p is now undefined and the The value of p is now undefined and the memory used by the variable that p memory used by the variable that p pointed to is back in the freestorepointed to is back in the freestore

Page 19: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 19

Dangling PointersDangling Pointers

Using delete on a pointer variable destroys Using delete on a pointer variable destroys the dynamic variable pointed tothe dynamic variable pointed to

If another pointer variable was pointing to If another pointer variable was pointing to the dynamic variable, that variable is also the dynamic variable, that variable is also undefinedundefined

Undefined pointer variables are calledUndefined pointer variables are calleddangling pointers dangling pointers Dereferencing a dangling pointer (*p) is Dereferencing a dangling pointer (*p) is

usually disasteroususually disasterous

Page 20: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 20

Automatic VariablesAutomatic Variables

Variables declared in a function are Variables declared in a function are created by C++ and destroyed when the created by C++ and destroyed when the function endsfunction ends These are called These are called automatic variablesautomatic variables

because their creation and destruction is because their creation and destruction is controlled automaticallycontrolled automatically

The programmer manually controls The programmer manually controls creation and destruction of pointer creation and destruction of pointer variables with operators new and delete variables with operators new and delete

Page 21: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 21

Global VariablesGlobal Variables

Variables declared outside any function Variables declared outside any function definition are definition are global variablesglobal variables Global variables are available to all parts Global variables are available to all parts

of a programof a program Global variables are not generally used Global variables are not generally used

as errors involving them are often hard as errors involving them are often hard to find.to find.

Page 22: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 22

Type DefinitionsType DefinitionsA name can be assigned to a type definition, A name can be assigned to a type definition, then used to declare variablesthen used to declare variables

The keyword typedef is used to define new The keyword typedef is used to define new type namestype names Syntax: Syntax:

typedef Known_Type_Definition typedef Known_Type_Definition New_Type_Name;New_Type_Name;

Known_Type_Definition can be any Known_Type_Definition can be any typetype

Page 23: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 23

Defining Pointer TypesDefining Pointer TypesTo avoid mistakes using pointers, define a To avoid mistakes using pointers, define a pointer type namepointer type name ExampleExample

typedeftypedef int* IntPtr;int* IntPtr; Defines a new type, IntPtr, for pointer Defines a new type, IntPtr, for pointer

variables containing pointers to int variablesvariables containing pointers to int variables

IntPtr p;IntPtr p;

is equivalent tois equivalent to

int *p; int *p;

Page 24: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 24

Multiple Declarations AgainMultiple Declarations Again

Using our new pointer type defined as Using our new pointer type defined as typedef int* IntPtr; typedef int* IntPtr; Prevent this error in pointer declaration:Prevent this error in pointer declaration:

int *P1, P2; int *P1, P2; Only P1 is a pointer variableOnly P1 is a pointer variable with with

IntPtr P1, P2; IntPtr P1, P2; P1 and P2 are pointer variablesP1 and P2 are pointer variables

Page 25: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 25

Pointer Reference ParametersPointer Reference Parameters

A second advantage in using typedef to A second advantage in using typedef to define a pointer type is seen in parameter define a pointer type is seen in parameter listslists Example: Example:

void sample_function(IntPtr& pointer_var);void sample_function(IntPtr& pointer_var); is less confusing than is less confusing than

void sample_function( int*& pointer_var);void sample_function( int*& pointer_var);

Page 26: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 26

Section 9.1 ConclusionSection 9.1 ConclusionCan youCan you Declare a pointer variable?Declare a pointer variable? Assign a value to a pointer variable?Assign a value to a pointer variable? Use the new operator to create a new Use the new operator to create a new

variable in the freestore?variable in the freestore? Write a definition for a type called Write a definition for a type called

NumberPtr to be a type for pointers to NumberPtr to be a type for pointers to dynamic variables of type int?dynamic variables of type int?

Use the NumberPtr type to declare a Use the NumberPtr type to declare a pointer variable called my_point?pointer variable called my_point?

Page 27: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

9.29.2Dynamic ArraysDynamic Arrays

Page 28: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 28

Dynamic ArraysDynamic Arrays

A A dynamic arraydynamic array is an array whose size is is an array whose size is determined when the program is running, determined when the program is running, not when you write the programnot when you write the program

Many programming languages do not allow Many programming languages do not allow dynamic arrays.dynamic arrays.

In fact, originally the word In fact, originally the word arrayarray meant a meant a fixed size.fixed size.

Page 29: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 29

Pointer Variables and Array VariablesPointer Variables and Array VariablesArray variables are actually pointer variables Array variables are actually pointer variables that point to the first indexed variablethat point to the first indexed variable Example: Example: int a[10];int a[10];

typedef int* IntPtr;typedef int* IntPtr; IntPtr p; IntPtr p;

Variables a and p are the same kind of Variables a and p are the same kind of variablevariable

Since a is a pointer variable that points to a[0],Since a is a pointer variable that points to a[0], p = a; p = a;causes p to point to the same location as acauses p to point to the same location as a

Page 30: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Continuing the previous example:Continuing the previous example:Pointer variable p can be used as if it were an Pointer variable p can be used as if it were an array variablearray variable

Example: Example: p[0], p[1], …p[9] p[0], p[1], …p[9] are all legal ways to use p are all legal ways to use p

Variable a can be used as a pointer variable Variable a can be used as a pointer variable except the pointer value in a cannot be changedexcept the pointer value in a cannot be changed

This is not legal: This is not legal: IntPtr p2;IntPtr p2;

… // p2 is assigned a value … // p2 is assigned a value a = p2 // attempt to change a a = p2 // attempt to change a

Slide 9- 30

Pointer Variables As Array VariablesPointer Variables As Array Variables

Page 31: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 32: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 32

Creating Dynamic ArraysCreating Dynamic ArraysNormal arrays require that the programmer Normal arrays require that the programmer determine the size of the array when the determine the size of the array when the program is writtenprogram is written What if the programmer estimates too large?What if the programmer estimates too large?

Memory is wastedMemory is wasted What if the programmer estimates too small?What if the programmer estimates too small?

The program may not work in some The program may not work in some situationssituations

Dynamic arrays can be created with just the Dynamic arrays can be created with just the right size while the program is runningright size while the program is running

Page 33: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 33

Dynamic arrays are created using the new Dynamic arrays are created using the new operatoroperator Example: To create an array of 10 Example: To create an array of 10

elements of type double:elements of type double: typedef double* DoublePtr; typedef double* DoublePtr; DoublePtr d; DoublePtr d; d = new double[10]; d = new double[10];

d can now be used as if it were an d can now be used as if it were an ordinary array! ordinary array!

This could be an integer variable!

Creating Dynamic ArraysCreating Dynamic Arrays

Page 34: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Pointer variable d is a pointer to d[0]Pointer variable d is a pointer to d[0]

When finished with the array, it should be When finished with the array, it should be deleted to return memory to the freestoredeleted to return memory to the freestore Example: delete [ ] d;Example: delete [ ] d;

The brackets tell C++ a dynamic array is being The brackets tell C++ a dynamic array is being deleted so it must check the size to know how deleted so it must check the size to know how many indexed variables to removemany indexed variables to remove Forgetting the brackets, is not legal, but Forgetting the brackets, is not legal, but

would tell the computer to remove only one would tell the computer to remove only one variablevariable

Slide 9- 34

Dynamic Arrays (cont.)Dynamic Arrays (cont.)

Page 35: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 36: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 37: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 37

Pointer ArithmeticPointer ArithmeticArithmetic can be performed on the addresses Arithmetic can be performed on the addresses contained in pointerscontained in pointers Using the dynamic array of doubles, d, Using the dynamic array of doubles, d,

declared previously, recall that d points to declared previously, recall that d points to d[0]d[0]

The expression d+1 evaluates to the The expression d+1 evaluates to the address of d[1] and d+2 evaluates to the address of d[1] and d+2 evaluates to the address of d[2]address of d[2]

Notice that adding one adds enough bytes Notice that adding one adds enough bytes for one variable of the type stored in the for one variable of the type stored in the array array

Page 38: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 38

Pointer Arithmetic OperationsPointer Arithmetic OperationsYou can add and subtract with pointersYou can add and subtract with pointers The ++ and - - operators can be usedThe ++ and - - operators can be used Two pointers of the same type can be Two pointers of the same type can be

subtracted to obtain the number of indexed subtracted to obtain the number of indexed variables betweenvariables between

The pointers should be in the same array!The pointers should be in the same array! This code shows one way to use pointer This code shows one way to use pointer

arithmetic:arithmetic: for (int i = 0; i < array_size; i++) for (int i = 0; i < array_size; i++) cout << *(d + i) << " " ; cout << *(d + i) << " " ; // same as cout << d[i] << " " ; // same as cout << d[i] << " " ;

Page 39: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 39

Multidimensional Dynamic ArraysMultidimensional Dynamic Arrays

To create a 3x4 multidimensional dynamic arrayTo create a 3x4 multidimensional dynamic array View multidimensional arrays as arrays of View multidimensional arrays as arrays of

arraysarrays First create a one-dimensional dynamic arrayFirst create a one-dimensional dynamic array

Start with a new definition: Start with a new definition: typedef int* IntArrayPtr;typedef int* IntArrayPtr;

Page 40: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Now create a dynamic array of pointers Now create a dynamic array of pointers named m: named m: IntArrayPtr *m = new IntArrayPtr[3];IntArrayPtr *m = new IntArrayPtr[3]; For each pointer in m, create a dynamic For each pointer in m, create a dynamic

array of int'sarray of int's

for (int i = 0; i<3; i++)for (int i = 0; i<3; i++) m[i] = new int[4]; m[i] = new int[4];

Page 41: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 41

mIntArrayPtr's

int's

IntArrayPtr *

A Multidimensional Dynamic ArrayA Multidimensional Dynamic ArrayThe dynamic array created on the previous The dynamic array created on the previous slide could be visualized like this:slide could be visualized like this:

Page 42: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

To delete a multidimensional dynamic arrayTo delete a multidimensional dynamic array Each call to new that created an array must Each call to new that created an array must

have a corresponding call to delete[ ]have a corresponding call to delete[ ] Example: To delete the dynamic array Example: To delete the dynamic array

created on a previous slide:created on a previous slide: for ( i = 0; i < 3; i++) for ( i = 0; i < 3; i++) delete [ ] m[i]; //delete the arrays of 4 delete [ ] m[i]; //delete the arrays of 4 int'sint's

delete [ ] m; // delete the array of IntArrayPtr'sdelete [ ] m; // delete the array of IntArrayPtr's

Slide 9- 42

Deleting Multidimensional ArraysDeleting Multidimensional Arrays

Page 43: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 44: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Page 45: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 45

Section 9.2 ConclusionSection 9.2 ConclusionCan youCan you Write a definition for pointer variables that will be Write a definition for pointer variables that will be

used to point to dynamic arrays? The array used to point to dynamic arrays? The array elements are of type char. Call the type elements are of type char. Call the type CharArray.CharArray.

Write code to fill array "entry" with 10 numbers Write code to fill array "entry" with 10 numbers typed at the keyboard? typed at the keyboard? int * entry; int * entry; entry = new int[10]; entry = new int[10];

Page 46: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.

Slide 9- 46

Chapter 9 -- EndChapter 9 -- End


Recommended