coen 244 - 8 - pointers and pointer-based strings

38
2008 Pearson Education, Inc. All rights rese 1 8 Pointers and Pointer-Based Strings

Upload: maxime-pauloin

Post on 31-Jan-2016

229 views

Category:

Documents


0 download

DESCRIPTION

COEN 244

TRANSCRIPT

Page 1: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

1

88

Pointers andPointer-Based

Strings

Page 2: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

2

8.1 Introduction

• Pointers – Powerful, but difficult to master

– Can be used to pass arguments to a function

– Can be used to create and manipulate dynamic data structures

– Have close relationship with arrays and strings

Page 3: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

3

8.2 Pointer Variable Declarations and Initialization

• Pointers are variables that contain memory addresses as values

• Normally, variable contains specific value (direct reference)

• Pointers contain address of a variable that has specific value (indirect reference)

Page 4: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

4

8.2 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)

Page 5: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

5

Fig. 8.1 | Directly and indirectly referencing a variable.

Page 6: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

6

8.3 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

Page 7: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

7

Fig. 8.2 | Graphical representation of a pointer pointing to a variable in memory.

Page 8: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

8

8.3 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

Page 9: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

9

Fig. 8.3 | Representation of y and yPtr in memory.

Page 10: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

10Outline

fig08_04.cpp

(1 of 2)

1 // Fig. 8.4: fig08_04.cpp

2 // Using the & and * operators.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6

7 int main()

8 {

9 int a; // a is an integer

10 int *aPtr; // aPtr is an int * -- pointer to an integer

11

12 a = 7; // assigned 7 to a

13 aPtr = &a; // assign the address of a to aPtr

Variable aPtr is a point to an int

Initialize aPtr with the address of variable a

Page 11: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

11Outline

fig08_04.cpp

(2 of 2)

14

15 cout << "The address of a is " << &a

16 << "\nThe value of aPtr is " << aPtr;

17 cout << "\n\nThe value of a is " << a

18 << "\nThe value of *aPtr is " << *aPtr;

19 cout << "\n\nShowing that * and & are inverses of "

20 << "each other.\n&*aPtr = " << &*aPtr

21 << "\n*&aPtr = " << *&aPtr << endl;

22 return 0; // indicates successful termination

23 } // end main The address of a is 0012F580 The value of aPtr is 0012F580 The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 0012F580 *&aPtr = 0012F580

* and & are inverses of each other

Address of a and the value of aPtr are identical

* and & are inverses; same result when both are applied to aPtr

Value of a and the dereferenced aPtr are identical

Page 12: COEN 244 - 8 - Pointers and Pointer-Based Strings

A pointer may be related to a variable in four ways

1.Non-Constant pointer to Non-Constant data 2. Non-Constant pointer to Constant dataint main ( ) int main ( ){ {

int x = 10, y =20; int x = 10, y =20;int *ptr = &x; const int *ptr = &x;*ptr = 15; // x=15 *ptr = 15; // Not permittedptr = &y; ptr = &y; // Permitted*ptr = 25; // y=25 *ptr = 25; // Not permittedreturn 0; return 0;

} }

Page 13: COEN 244 - 8 - Pointers and Pointer-Based Strings

A pointer to variable relation continued…

3. Constant pointer to Non-Constant data 4. Constant pointer to Constant data

int main ( ) int main ( ){ {

int x = 10, y =20; int x = 10, y =20;int * const ptr = &x; const int * const ptr = &x;*ptr = 15; // Permitted, x=15 *ptr = 15; // Not permittedptr = &y; // Not permitted ptr = &y; // Not Permitted

return 0; return 0;} }

Page 14: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

14

8.4 Passing Arguments to Functions by Reference with Pointers

• Pointers may be used to pass arguments to a function, which is known as,

– Pass-by-reference with pointer arguments

This is accomplished by,– Passing address of the argument using & operator

– Arrays not passed with & because array name is already a pointer

Page 15: COEN 244 - 8 - Pointers and Pointer-Based Strings

A pointer may be passed to a function in four ways

1. Non-Constant pointer to Non-Constant Data 2. Non-Constant pointer to Constant Data#include <iostream.h>

#include <iostream.h>void f ( int * );

void f ( const int * );

int main ( ) int main ( ){ { int x = 10; int x = 10; f ( &x) ; f ( &x) ; return 0; return 0;} }

void f ( int *xPtr) void f ( const int *xPtr ){ { int y = 20; int y = 20;*xPtr = 100 ; // Permitted *xPtr = 100 ; // Not permittedxPtr = &y; // Permitted xPtr = &y; // Permitted} }

Page 16: COEN 244 - 8 - Pointers and Pointer-Based Strings

A Pointer to a function passing continued…

3. Constant pointer to Non-constant Data 4. Constant pointer to Constant Data

#include <iostream.h> #include <iostream.h>

void f ( int * const); void f ( const int * const);

int main ( ) int main ( ){ int x = 10; { int x = 10; f ( &x) ; f ( &x) ; return 0; return 0;}

}

void f ( int * const xPtr) void f ( const int * const xPtr){ int y = 20; { int y = 20;*xPtr = 100 ; // Permitted *xPtr = 100 ; // Not permittedxPtr = &y; // Not Permitted xPtr = &y ; // Not permitted} }

Page 17: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

17

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function– Nonconstant pointer to nonconstant data

• Highest amount of access

• Data can be modified through the dereferenced pointer

• Pointer can be modified to point to other data

• Its declaration does not include const qualifier

Page 18: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

18

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)– Nonconstant pointer to constant data

• Pointer can be modified to point to any appropriate data item

• Data cannot be modified through this pointer

• Provides the performance of pass-by-reference and the protection of pass-by-value

Page 19: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

19

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)– Constant pointer to nonconstant data

• Always points to the same memory location

• Data can be modified through the pointer

• Default for an array name

– Can be used by a function to receive an array argument

• Must be initialized when declared

Page 20: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

20

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)– Constant pointer to constant data

• Least amount of access

• Always points to the same memory location

• Data cannot be modified using this pointer

Page 21: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

21

8.8 Arrays and Pointers

• int v[5]; //5 element int array on a machine

using 4 byte ints - vPtr = v; vPtr points to the first

element v[0], at location v[0]

– vPtr = &v[ 0 ]; vPtr points to first element v[ 0 ],

at location 3000

Page 22: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

22

8.8 Pointer Expressions and Pointer Arithmetic (Cont.)

– 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

– vPtr += 2; sets vPtr to 3008 (3000 + 2 * 4)

vPtr points to v[ 2 ]

– Returns number of elements between two addresses

vPtr2 = &v[ 2 ];vPtr = &v[ 0 ];vPtr2 - vPtr is 2

Page 23: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

23

Fig. 8.18 | Array v and a pointer variable vPtr that points to v.

Page 24: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

24

Fig. 8.19 | Pointer vPtr after pointer arithmetic.

Page 25: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

25

8.8 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 *

(void *ptr; int *y, x=5; y = &x; ptr=y;)

• Casting is needed to convert void * to any other type

• void pointers cannot be dereferenced

Page 26: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

26

8.8 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)

Page 27: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

27

8.9 Relationship Between Pointers and Arrays

• Arrays and pointers are closely related– Array name is like a constant pointer

void f(int *);

int main( )

{ int v[5];

int a;

f( &a) ; passing a simple variable to the function f.

f ( v) ; passing an array to the unction f.

}

Page 28: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

28

8.9 Relationship Between Pointers and Arrays (Cont.)

– Pointers can do array subscripting operations

• Accessing array elements with pointers– Assume declarations:

int b[ 5 ]; int *bPtr; bPtr = b;

– An array element b[ n ] can be accessed by using pointer/offset notation,

*( bPtr + n ) or *(b+n)

– Pointers can be subscripted like an array (pointer/subscript notation)

• bPtr[ 3 ] is same as b[ 3 ]

Page 29: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

29

8.13.1 Fundamentals of Characters and Pointer-Based Strings (Cont.)

• String assignment– Character array

• char color[] = "blue";

– Creates 5 element char array color

• Last element is '\0'

– Variable of type char *• char *colorPtr = "blue";

– Creates pointer colorPtr to letter b in string "blue"

• "blue’\0’" somewhere in memory

– Alternative for character array• char color[] = { 'b', 'l', 'u', 'e', '\0' };

Page 30: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

30Outline

fig08_21.cpp

(1 of 2)

Page 31: COEN 244 - 8 - Pointers and Pointer-Based Strings

2008 Pearson Education, Inc. All rights reserved.

31Outline

fig08_21.cpp

(2 of 2)

Use array subscript notation to copy string in s2 to character array s1

Use pointer notation to copy string in s2 to character array in s1

Increment both pointers to point to next elements in corresponding arrays

Page 32: COEN 244 - 8 - Pointers and Pointer-Based Strings

Function Parameter Passing and Return Types

There are three types of function parameter passing and returning values. Function parameter type passing can be chosen independent of the type of the function return.

•Parameter Passing 1. Pass-by-value A copy of the variable is passed to the function. Variable cannot be modified by the function.Example: void modify ( int ) int main ( ) { int a = 4; modify ( a ); cout << a << endl; // a = 4; return 0; } void modify (int b) { b += 6; }

Comment : The value of variable a in the main program remained same. Performance disadvantage: overhead of copying.

Page 33: COEN 244 - 8 - Pointers and Pointer-Based Strings

2. Pass-by-reference using a reference parameter

A function may modify a variable directly. Example :

void modify ( int &) int main ( ) { int a = 4; modify ( a ); cout << a << endl; // a= 10 return 0; } void modify ( int &b) { b +=6; }

Comment : The value of variable a in the main program has changed. No performance disadvantage.

Page 34: COEN 244 - 8 - Pointers and Pointer-Based Strings

3. Pass-by-reference using pointers

A function may modify a variable directly. Example :

void modify ( int * ) int main ( ) { int a = 4; modify ( &a ); cout << a << endl; // a= 10 return 0; } void modify ( int *b) { *b +=6; }

Comment : The value of variable a in the main program has changed.

No performance disadvantage.

 

Page 35: COEN 244 - 8 - Pointers and Pointer-Based Strings

Observations:

•Function calls in the case of pass-by-value and pass-by-reference using reference parameter are identical. Thus from the function calls it is not possible to determine which type of these two calls are being used. In the above function calls in both cases are: modify ( a ). Further inside the function parameter is being used identically, as b in the above function modify. We can determine type of parameter passing from the function prototypes or function header.•Function parameter passing using reference parameter and pointers may also be distinguished from the function prototype or function header. Thus & in the prototype indicates reference parameter and * in the prototype indicates parameter passing by pointers.

Page 36: COEN 244 - 8 - Pointers and Pointer-Based Strings

•Function return types

There are three types of function return types.

1. Return through pass-by-valueA copy of the local variable in the function is returned to the calling program.Example:

int modify ( int ) int main ( ) { int a = 4;// the following call outputs 10. cout << modify ( a ) << endl; return 0; } int modify (int b) { b += 6; return b; }

Page 37: COEN 244 - 8 - Pointers and Pointer-Based Strings

2. Returning a reference

Do not return a reference to a local automatic variable, since such a variable will be destroyed as soon as the execution of the function is completed.

Example: In the following example the & sign in the function prototype and the header indicates that a reference is being returned. int &modify ( int )

int main ( ) { int a = 4;// In the following call c // becomes a reference to x.//Then c outputs the value of x. int &c = modify ( a ); cout << c << endl; return 0; } int &modify (int b) { static int x = 3; b += 2; x += b ;

return x ; }

Comment: In the above function returning a reference to variable x works because static variables exist for the entire duration of the program. On the other hand,

returning a reference to the variable b would not work since it is an automatic local variable.

Page 38: COEN 244 - 8 - Pointers and Pointer-Based Strings

3.Returning a pointer

Do not return a pointer to a local automatic variable, since such a variable will be destroyed as soon as the execution of the function is completed.

Example: In the following example the * sign in the function prototype and header indicates that a pointer is being returned. int *modify ( int )

int main ( ) { int *c = 0; int a = 4; // In the following c is assigned // the address of x. //The referencing c outputs // the value of x. c = modify ( a ); cout << *c << endl; return 0; } int *modify (int b) { static int x = 3; b += 2; x += b ;

return &x ; }

Comment: In the above function returning a pointer to variable x works because static variables exist for the entire duration of the program. On the other hand, returning a reference to the variable b would not work since it is an automatic local variable.