Professional Documents
Culture Documents
Chapter 5 - Pointers: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 5 - Pointers: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 5 - Pointers: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 5 - Pointers
Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Passing parameters 5.5 Using const with Pointers 5.6 sizeof Operator 5.7 Pointer Expressions and Pointer Arithmetic 5.8 Relationship Between Pointers and Arrays 5.9 Arrays of Pointers 5.10 Function Pointers
Indirection
Referencing value through pointer
Indirection
Referencing value through pointer
Pointer declarations
* indicates variable is pointer
int *myPtr;
declares pointer to int, pointer of type int * Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
2003 Prentice Hall, Inc. All rights reserved.
5.2 Pointer Variable Declarations and Initialization Can declare pointers to any data type
House *phouse; Computer *pcomputer; List<Point> *plist;
5.2 Pointer Variable Declarations and Initialization Can declare pointers to any data type
House *phouse; Computer *pcomputer; List<Point> *plist;
Pointer initialization
Initialized to 0, NULL, or address
0 or NULL points to nothing House *phouse = 0; Computer *pcomputer = 0; List<Point> *plist = 0;
yPtr points to y
yPtr points to y
y 5 yptr 500000 600000 600000 y 5
yPtr
10
yPtr points to y
y 5 yptr 500000 600000 600000 y 5
yPtr
11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Fig. 5.4: fig05_04.cpp // Using the & and * operators. #include <iostream> using std::cout; using std::endl; int main() { int a; int *aPtr; a = 7; aPtr = &a;
Outline
fig05_04.cpp (1 of 2)
12
cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr; cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr; cout << "\n\nShowing that * and & are inverses of " << "each other.\n&*aPtr = " << &*aPtr << "\n*&aPtr = " << *&aPtr << endl;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Fig. 5.4: fig05_04.cpp // Using the & and * operators. #include <iostream> using std::cout; using std::endl; int main() { int a; int *aPtr; a = 7; aPtr = &a;
Outline
fig05_04.cpp (1 of 2)
13
The address of a is 0012FED4 The value of aPtr is 0012FED4 The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 0012FED4 *&aPtr = 0012FED4
cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr; cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr; cout << "\n\nShowing that * and & are inverses of " << "each other.\n&*aPtr = " << &*aPtr << "\n*&aPtr = " << *&aPtr << endl;
14
15
return can return one value from function Arguments passed to function using reference arguments
Modify original values of arguments More than one value returned
16
Pass address of argument using & operator Arrays not passed with & because array name already pointer * operator used as alias/nickname for variable inside of function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Fig. 5.6: fig05_06.cpp // Cube a variable using pass-by-value. #include <iostream> using std::cout; using std::endl; int cubeByValue( int ); int main() { int number = 5; cout << "The original value of number is " Passnumber; << number // pass number by value to cubeByValue number = cubeByValue( number ); // prototype
Outline
fig05_06.cpp (1 of 2)
17
cout << "\nThe new value of number is " << number << endl; return 0; } // end main // indicates successful termination
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Fig. 5.6: fig05_06.cpp // Cube a variable using pass-by-value. #include <iostream> using std::cout; using std::endl; int cubeByValue( int ); int main() { int number = 5; cout << "The original value of number is " Passnumber; << number // pass number by value to cubeByValue number = cubeByValue( number ); // prototype
Outline
fig05_06.cpp (1 of 2)
18
cout << "\nThe new value of number is " << number << endl; return 0; } // end main // indicates successful termination The original value of number is 5 The new value of number is 125
// calculate and return cube of integer argument cubeByValue int cubeByValue( int n ) passed-by-value { return n * n * n; // cube local variable n and return result } // end function cubeByValue
receives parameter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 5.7: fig05_07.cpp // Cube a variable using pass-by-reference // with a pointer argument. #include <iostream> using std::cout; using std::endl; void cubeByReference( int * ); int main() { int number = 5; cout << "The original value of number is " << number; // pass address of number to cubeByReference( &number );
Outline
Prototype indicates parameter is pointer to int fig05_07.cpp (1 of 2)
19
// prototype
cout << "\nThe new value of number is " << number << endl; return 0; } // end main // indicates successful termination
26 27 28 29 30 31
// calculate cube of *nPtr; modifies variable number in main void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr } // end function cubeByReference
Outline
fig05_07.cpp (2 of 2) fig05_07.cpp output (1 of 1)
20
21
22
Nonconstant pointer to constant data Constant pointer to nonconstant data Constant pointer to constant data
Least amount of access
2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 5.10: fig05_10.cpp // Converting lowercase letters to uppercase letters // using a non-constant pointer to non-constant data. #include <iostream> using std::cout; using std::endl; #include <cctype> // prototypes for
Outline
fig05_10.cpp (1 of 2)
23
void convertToUppercase( char * ); int main() { char phrase[] = "characters and $32.98";
cout << "The phrase before conversion is: " << phrase; convertToUppercase( phrase ); cout << "\nThe phrase after conversion is: " << phrase << endl; return 0; } // end main // indicates successful termination
26 27 28 29 30 31 32 33 34 35 36 37 38 The The
// convert string to uppercase letters void convertToUppercase( char *sPtr ) { while ( *sPtr != '\0' ) { // current character is not '\0' if ( islower( *sPtr ) ) // if character *sPtr = toupper( *sPtr ); // convert to uppercase ++sPtr; // move
Outline
24
fig05_10.cpp Parameter sPtr nonconstant (2 of 2) is lowercase, pointer to nonconstant data fig05_10.cpp output (1 of 1)
} // end while
Function islower returns sPtr to next character in string true if character is lowercase
Function toupper returns } // end function convertToUppercase corresponding ++ applied When operatoruppercase to character if points to array, pointer that original character phrase before conversion is: characters and $32.98 lowercase; otherwise memory address stored in phrase after conversion is: CHARACTERS AND $32.98 toupper returns original pointer modified to point to (uppercase) character next element of array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 5.11: fig05_11.cpp // Printing a string one character at a time using // a non-constant pointer to constant data. #include <iostream> using std::cout; using std::endl; void printCharacters( const char * ); int main() { Pass pointer char phrase[] = "print characters of a string"; cout << "The string is:\n"; printCharacters( phrase ); cout << endl; return 0; } // end main
Outline
fig05_11.cpp (1 of 2)
25
phrase to
function printCharacters.
23 24 25 26 27 28 29 30
// sPtr cannot modify the character to which it points, // i.e., sPtr is a "read-only" pointer void printCharacters( const char *sPtr ) { for ( ; *sPtr != '\0'; sPtr++ ) // no initialization sPtr is nonconstant cout << *sPtr; } // end function printCharacters
Outline
fig05_11.cpp (2 of 2) fig05_11.cpp output (1 of 1)
26
pointer to constant data; cannot modify character to which sPtr points. Increment sPtr to point to next character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 5.12: fig05_12.cpp // Attempting to modify data through a // non-constant pointer to constant data. void f( const int * ); int main() { int y; f( &y ); return 0; } // end main // prototype
Outline
fig05_12.cpp (1 of 1) fig05_12.cpp output (1 of 1)
27
// xPtr cannot modify the value of the variable Attempt to modify const // to which it points object pointed to by xPtr. void f( const int *xPtr ) { *xPtr = 100; // error: cannot modify a const object } // end function f
28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Fig. 5.13: fig05_13.cpp // Attempting to modify a constant pointer to // non-constant data. int main() { int x, y;
Outline
fig05_13.cpp (1 of 1) fig05_13.cpp output (1 of 1)
29
ptr that can // ptr is a constant pointer to an integer is constant pointer // be modified through ptr, but ptr x (pointed to byto the integer. Can modify always points // same memory location. ptr) since x not constant. Cannot modify ptr to point int * const ptr = &x;
*ptr = 7; ptr = &y; return 0; } // end main
to
// allowed: // error: ptr is const; cannot assign new address // indicates successful
Line 15 generates compiler error by attempting to assign termination new address to constant pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Fig. 5.14: fig05_14.cpp // Attempting to modify a constant pointer to constant data. #include <iostream> using std::cout; using std::endl; int main() { int x = 5, y;
Outline
fig05_14.cpp (1 of 1)
30
ptr is integer. // ptr is a constant pointer to a constant constant pointer integer the integer // ptr always points to the same location; constant. // at that location cannot be modified. const int *const ptr = &x;
cout
to
Cannot modify x (pointed to by ptr) since *ptrto point Cannot modify ptr declared << *ptr << endl; constant. to new address since ptr is = 7; // error: *ptrconstant. is const; cannot assign new
// indicates successful termination
} // end main
d:\cpphtp4_examples\ch05\Fig05_14.cpp(19) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch05\Fig05_14.cpp(20) : error C2166: l-value specifies const object
Outline
31
fig05_14.cpp Line 19 generates compiler output (1 of 1) error by attempting to modify Line 20 generates compiler constant object. error by attempting to assign new address to constant pointer.
32
33
v[0]
v[1]
v[2]
v[3]
v[4]
34
35
Pointer assignment
Pointer can be assigned to another pointer if both 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 pointer void pointers cannot be dereferenced
2003 Prentice Hall, Inc. All rights reserved.
36
5.8 Relationship Between Pointers and Arrays Arrays and pointers closely related
Array name like constant pointer Pointers can do array subscripting operations
37
5.8 Relationship Between Pointers and Arrays Arrays and pointers closely related
Array name like constant pointer Pointers can do array subscripting operations
38
Addresses
&b[ 3 ] same as bPtr + 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 5.20: fig05_20.cpp // Using subscripting and pointer notations with arrays. #include <iostream> using std::cout; using std::endl; int main() { int b[] = { 10, 20, 30, 40 }; int *bPtr = b; // set bPtr to point to array b // output array b using array subscript notation cout << "Array b printed with:\n" << "Array subscript notation\n"; for ( int i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << '\n'; // output array b using the array name and // pointer/offset notation cout << "\nPointer/offset notation where " << "the pointer is the array name\n";
Outline
fig05_20.cpp (1 of 2)
39
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
for ( int offset1 = 0; offset1 < 4; offset1++ ) cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << '\n'; // output array b using bPtr and array subscript notationand Using array name cout << "\nPointer subscript notation\n"; for ( int j = 0; j < 4; j++ ) cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; cout << "\nPointer/offset notation\n"; // output array b using bPtr and pointer/offset for ( int offset2 = 0; offset2 < 4; offset2++ ) cout << "*(bPtr + " << offset2 << ") = " << *( bPtr + offset2 ) << '\n'; return 0; } // end main // indicates successful termination
Outline
fig05_20.cpp (2 of 2)
40
pointer/offset notation.
Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40 Pointer/offset notation where the pointer is the array name *(b + 0) = 10 *(b + 1) = 20 *(b + 2) = 30 *(b + 3) = 40 Pointer bPtr[0] bPtr[1] bPtr[2] bPtr[3] subscript notation = 10 = 20 = 30 = 40
Outline
fig05_20.cpp output (1 of 1)
41
42
43
OR
compare( int1, int2 ) Could be confusing User may think compare name of actual function in program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 5.25: fig05_25.cpp // Multipurpose sorting program using function pointers. #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setw; // prototypes void bubble( int [], const int, bool (*)( int, int ) void swap( int * const, int * const ); bool ascending( int, int ); bool descending( int, int );
Outline
fig05_25.cpp (1 of 5)
44
Parameter is pointer to function that receives two integer parameters and returns ); bool result.
int main() { const int arraySize = 10; int order; int counter; int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
cout << "Enter 1 to sort in ascending order,\n" << "Enter 2 to sort in descending order: "; cin >> order; cout << "\nData items in original order\n"; // output original array for ( counter = 0; counter < arraySize; counter++ ) cout << setw( 4 ) << a[ counter ]; // sort array in ascending order; pass function ascending // as an argument to specify ascending sorting order if ( order == 1 ) { bubble( a, arraySize, ascending ); cout << "\nData items in ascending order\n"; } // sort array in descending order; pass function descending // as an agrument to specify descending sorting order else { bubble( a, arraySize, descending ); cout << "\nData items in descending order\n"; }
Outline
fig05_25.cpp (2 of 5)
45
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// output sorted array for ( counter = 0; counter < arraySize; counter++ ) cout << setw( 4 ) << a[ counter ]; cout << endl; return 0; } // end main // multipurpose bubble sort; parameter compare is a pointer to // the comparison function that determines function that receives two sorting order integer parameters and returns void bubble( int work[], const int size, bool (*compare)( int, int ) ) bool result. { // loop to control passes Parentheses necessary to for ( int pass = 1; pass < size; pass++ ) // indicates successful termination
Outline
fig05_25.cpp (3 of 5)
46
compare is pointer to
// loop to control number of comparisons per pass Call passed function for ( int count = 0; count < size - 1; count++ )
// if adjacent elements if ( (*compare)( work[ count ], work[ count + 1 ] ) ) swap( &work[ count ], &work[ count + 1 ] );
compare; dereference are pointer to execute function. out of order, swap them
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
} // end function bubble // swap values at memory locations to which // element1Ptr and element2Ptr point void swap( int * const element1Ptr, int * const element2Ptr ) { int hold = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = hold; } // end function swap // determine whether elements are out of order // for an ascending order sort bool ascending( int a, int b ) { return b < a; // swap if b is less than a } // end function ascending
Outline
fig05_25.cpp (4 of 5)
47
94 95 96 97 98 99 100
// determine whether elements are out of order // for a descending order sort bool descending( int a, int b ) { return b > a; // swap if b is greater than a } // end function descending
Outline
fig05_25.cpp (5 of 5) fig05_25.cpp output (1 of 1)
48
Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 1 Data items in original order 2 6 4 8 10 12 89 68 Data items in ascending order 2 4 6 8 10 12 37 45 45 68 37 89
Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 2 Data items in original order 2 6 4 8 10 12 89 68 Data items in descending order 89 68 45 37 12 10 8 6
45 4
37 2