1 / 58

Object-Oriented Programming -- Using C++

Object-Oriented Programming -- Using C++. Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology andres@dlit.edu.tw http://cse.dlit.edu.tw/~andres. Chapter 5 - Pointers and Strings.

misty
Télécharger la présentation

Object-Oriented Programming -- Using C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object-Oriented Programming-- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology andres@dlit.edu.tw http://cse.dlit.edu.tw/~andres

  2. Chapter 5 - Pointers and Strings Outline5.1 Introduction5.2 Pointer Variable Declarations and Initialization5.3 Pointer Operators5.4 Calling Functions by Reference5.5 Using const with Pointers5.7 Pointer Expressions and Pointer Arithmetic5.8 Relationship Between Pointers and Arrays5.9 Arrays of Pointers5.12 Introduction to Character and String Processing 5.12.1 Fundamentals of Characters and Strings 5.12.2 String Manipulation Functions of the String- Handling Library

  3. 5.1 Introduction • Pointers • Powerful, but difficult to master • Simulate pass-by-reference • Close relationship with arrays and strings

  4. count countPtr myPtr count 7 7 5.2 Pointer Variable Declarations and Initialization • Pointer variables • Contain memory addresses as values • Normally, variable contains specific value (direct reference) • Pointers contain address of variable that has specific value (indirect reference) • Indirection • Referencing value through pointer • Pointer declarations • * indicates variable is pointer int *myPtr; declares pointer to an int, pointer of type int * • Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; int

  5. 5.2 Pointer Variable Declarations and Initialization • Can declare pointers to any data type • Pointer initialization • Initialized to 0, NULL, or address • 0 or NULL points to nothing

  6. yPtr y 500000 600000 600000 5 5.3 Pointer Operators • & (address operator) • Returns memory address of its operand • Example int y = 5;int *yPtr;yPtr = &y; // yPtr gets address of y • yPtr “points to” y y 5 yPtr

  7. 5.3 Pointer Operators • *(indirection/dereferencing operator) • Returns synonym for object its pointer operand points to • *yPtr returns y (because yPtr points to y). • dereferenced pointer is lvalue *yptr = 9; // assigns 9 to y • * and & are inverses of each other

  8. 10 int a; // a is an integer 11 int *aPtr; // aPtr is a pointer to an integer 13 a = 7; 14 aPtr = &a; // aPtr assigned address of a 15 16 cout << "The address of a is " << &a 17 << "\nThe value of aPtr is " << aPtr; 18 19 cout << "\n\nThe value of a is " << a 20 << "\nThe value of *aPtr is " << *aPtr; 21 22 cout << "\n\nShowing that * and & are inverses of " 23 << "each other.\n&*aPtr = " << &*aPtr 24 << "\n*&aPtr = " << *&aPtr << endl; aPtr a 12FED4 12FED4 7 fig05_04.cpp(1 of 2) 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

  9. 5.4 Calling Functions by Reference • 3 ways to pass arguments to function • Pass-by-value • Pass-by-reference with reference arguments • Pass-by-reference with pointer arguments • return can return one value from function • Arguments passed to function using reference arguments • Modify original values of arguments • More than one value “returned”

  10. 5.4 Calling Functions by Reference • Pass-by-reference with pointer arguments • Simulate pass-by-reference • Use pointers and indirection operator • 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

  11. 1 // Fig. 5.6: fig05_06.cpp 2 // Cube a variable using pass-by-value. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int cubeByValue( int ); // prototype 10 int main() 11 { 12 int number = 5; 14 cout << "The original value of number is " << number; 17 number = cubeByValue( number ); 19 cout << "\nThe new value of number is " << number << endl; 21 return0; 23 } 25 26 int cubeByValue( int n ) 27 { 28 return n * n * n; // cube local variable n and return result 30 } fig05_06.cpp(1 of 2) number 5 125 n undefined 5 undefined The original value of number is 5 The new value of number is 125

  12. 1 // Fig. 5.7: fig05_07.cpp 2 // Cube a variable using pass-by-reference 3 // with a pointer argument. 4 #include <iostream> 6 using std::cout; 7 using std::endl; 9 void cubeByReference( int * ); // prototype 11 int main() 12 { 13 int number = 5; 14 15 cout << "The original value of number is " << number; 18 cubeByReference( &number ); 20 cout << "\nThe new value of number is " << number << endl; 22 return0; 24 } 27 void cubeByReference( int *nPtr ) 28 { 29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr 31 } fig05_07.cpp(1 of 2) number 125 5 nPtr undefined The original value of number is 5 The new value of number is 125

  13. 5.5 Using const with Pointers • const qualifier • Value of variable should not be modified • const used when function does not need to change a variable • Principle of least privilege • Award function enough access to accomplish task, but no more • 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 • Nonconstant pointer to constant data • Constant pointer to nonconstant data • Constant pointer to constant data • Least amount of access

  14. 1 // Fig. 5.10: fig05_10.cpp 2 // Nonconstant pointer to nonconstant data 9 #include <cctype> // prototypes for islower and toupper 11 void convertToUppercase( char * ); 13 int main() 14 { 15 char phrase[] = "characters and $32.98"; 17 cout << "The phrase before conversion is: " << phrase; 18 convertToUppercase( phrase ); 19 cout << "\nThe phrase after conversion is: " 20 << phrase << endl; 22 return0; 24 } 27 void convertToUppercase( char *sPtr ) 28 { 29 while ( *sPtr != '\0' ) { // current character is not '\0' 31 if ( islower( *sPtr ) ) // if character is lowercase, 32 *sPtr = toupper( *sPtr ); // convert to uppercase 34 ++sPtr; // move sPtr to next character in string 36 } 38 } c h a r … \0 phrase C H A R sPtr The phrase before conversion is: characters and $32.98 The phrase after conversion is: CHARACTERS AND $32.98

  15. 5.5 Using const with Pointers • Four ways to pass pointer to function • Nonconstant pointer to nonconstant data • Nonconstant pointer to constant data • pointer can be modified to point to any data item • data to which it points cannot be modified through that pointer • Constant pointer to nonconstant data • Constant pointer to constant data • Least amount of access

  16. 1 // Fig. 5.11: fig05_11.cpp 2 // Nonconstant pointer to constant data 4 #include <iostream> 6 using std::cout; 7 using std::endl; 9 void printCharacters( const char * ); 11 int main() 12 { 13 char phrase[] = "print characters of a string"; 14 15 cout << "The string is:\n"; 16 printCharacters( phrase ); 17 cout << endl; 19 return0; 21 } 25 void printCharacters( const char *sPtr ) 26 { 27 for ( ; *sPtr != '\0'; sPtr++ ) // no initialization 28 cout << *sPtr; 30 } p r i n … \0 fig05_11.cpp(1 of 2) phrase const char xPtr The string is: print characters of a string

  17. 1 // Fig. 5.12: fig05_12.cpp 2 // Nonconstant pointer to constant data 5 void f( const int * ); // prototype 7 int main() 8 { 9 int y; 11 f( &y ); // f attempts illegal modification 13 return0; // indicates successful termination 15 } // end main 16 19 void f( const int *xPtr ) 20 { 21 *xPtr = 100; // error: cannot modify a const object 23 } // end function f const int * xPtr fig05_12.cpp(1 of 1)fig05_12.cppoutput (1 of 1) y 100 d:\cpphtp4_examples\ch05\Fig05_12.cpp(21) : error C2166: l-value specifies const object

  18. 5.5 Using const with Pointers • Four ways to pass pointer to function • Nonconstant pointer to nonconstant data • Nonconstant pointer to constant data • Constant pointer to nonconstant data • pointer always points to the same memory location • data at that location can be modified through the pointer • Constant pointer to constant data • Least amount of access

  19. 1 // Fig. 5.13: fig05_13.cpp 2 // Attempting to modify a constant pointer to 3 // non-constant data. 5 int main() 6 { 7 int x, y; 12 int * const ptr = &x; 13 14 *ptr = 7; // allowed: *ptr is not const 15 ptr = &y; // error: ptr is const; cannot assign new address 17 return0; 19 } fig05_13.cpp(1 of 1)fig05_13.cppoutput (1 of 1) x y 7 int * const ptr d:\cpphtp4_examples\ch05\Fig05_13.cpp(15) : error C2166: l-value specifies const object

  20. 5.5 Using const with Pointers • Four ways to pass pointer to function • Nonconstant pointer to nonconstant data • Nonconstant pointer to constant data • Constant pointer to nonconstant data • Constant pointer to constant data • pointer always points to the same memory location • data at that location cannot be modified using the pointer • Least amount of access

  21. 1 // Fig. 5.14: fig05_14.cpp 2 // Attempting to modify a constant pointer to constant data. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int main() 9 { 10 int x = 5, y; 15 const int *const ptr = &x; 16 17 cout << *ptr << endl; 18 19 *ptr = 7; // error: *ptr is const; cannot assign new value 20 ptr = &y; // error: ptr is const; cannot assign new address 22 return0; 24 } fig05_14.cpp(1 of 1) 5 7 y int * const ptr const int x 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

  22. 5.5 Using const with Pointers • const pointers • Always point to same memory location • Default for array name • Must be initialized when declared

  23. location 3000 3004 3008 3012 3016 pointer variable vPtr v[0] v[1] v[2] v[4] v[3] 5.7 Pointer Expressions and Pointer Arithmetic • Pointer arithmetic • Increment/decrement pointer (++ or --) • Add/subtract an integer to/from a pointer( + or += , - or -=) • Pointers may be subtracted from each other • Pointer arithmetic meaningless unless performed on pointer to array • 5 element int array on a machine using 4 byte ints • vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000 • vPtr += 2; sets vPtr to 3008 vPtr points to v[ 2 ]

  24. 5.7 Pointer Expressions and Pointer Arithmetic • Subtracting pointers • Returns number of elements between two addresses vPtr2 = v[ 2 ];vPtr = v[ 0 ];vPtr2 - vPtr == 2 • Pointer assignment • Pointer can be assigned to another pointer if both of same type • If not same type, cast operator must be used

  25. 5.8 Relationship Between Pointers and Arrays • Arrays and pointers closely related • Array name like constant pointer • Pointers can do array subscripting operations • Accessing array elements with pointers • Element b[ n ] can be accessed by *( bPtr + n ) • Called pointer/offset notation • Addresses • &b[ 3 ] same as bPtr + 3 • Array name can be treated as pointer • b[ 3 ] same as *( b + 3 ) • Pointers can be subscripted (pointer/subscript notation) • bPtr[ 3 ] same as b[ 3 ]

  26. 1 // Fig. 5.20: fig05_20.cpp 11 int b[] = { 10, 20, 30, 40 }; 12 int *bPtr = b; // set bPtr to point to array b …… 18 for ( int i = 0; i < 4; i++ ) 19 cout << "b[" << i << "] = " << b[ i ] << '\n'; …… 26 for ( int offset1 = 0; offset1 < 4; offset1++ ) 27 cout << "*(b + " << offset1 << ") = " 28 << *( b + offset1 ) << '\n'; …… 33 for ( int j = 0; j < 4; j++ ) 34 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; …… 39 for ( int offset2 = 0; offset2 < 4; offset2++ ) 40 cout << "*(bPtr + " << offset2 << ") = " 41 << *( bPtr + offset2 ) << '\n'; 43 return0; 45 } fig05_20.cpp(1 of 2)

  27. 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 subscript notation bPtr[0] = 10 bPtr[1] = 20 bPtr[2] = 30 bPtr[3] = 40 Pointer/offset notation *(bPtr + 0) = 10 *(bPtr + 1) = 20 *(bPtr + 2) = 30 *(bPtr + 3) = 40 fig05_20.cppoutput (1 of 1)

  28. 1 // Fig. 5.21: fig05_21.cpp …… 9 void copy1( char *, const char * ); // prototype 10 void copy2( char *, const char * ); // prototype 12 int main() 13 { 14 char string1[ 10 ]; 15 char *string2 = "Hello"; 16 char string3[ 10 ]; 17 char string4[] = "Good Bye"; 18 19 copy1( string1, string2 ); 20 cout << "string1 = " << string1 << endl; 21 22 copy2( string3, string4 ); 23 cout << "string3 = " << string3 << endl; 25 return0; 27 } fig05_21.cpp(1 of 2)

  29. 30 void copy1( char *s1, const char *s2 ) 31 { 32 for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) 33 ; // do nothing in body 34 35 } 36 38 void copy2( char *s1, constchar *s2 ) 39 { 40 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) 41 ; // do nothing in body 43 } fig05_21.cpp(2 of 2)fig05_21.cppoutput (1 of 1) string1 = Hello string3 = Good Bye

  30. ’\0’ ’\0’ ’\0’ ’\0’ ’n’ ’d’ ’o’ ’u’ ’a’ ’s’ ’d’ ’b’ ’m’ ’H’ ’s’ ’a’ ’D’ ’i’ ’a’ ’s’ ’l’ ’C’ ’r’ ’s’ ’S’ ’p’ ’e’ ’t’ ’e’ suit[0] suit[1] suit[2] suit[3] 5.9 Arrays of Pointers • Arrays can contain pointers • Commonly used to store array of strings char *suit[ 4 ] = {"Hearts", "Diamonds","Clubs", "Spades" }; • Each element of suit points to char * (a string) • Array does not store strings, only pointers to strings • suit array has fixed size, but strings can be of any size

  31. Exercises #2 • 3.11 • 3.16 (b), (e), (f) • 3.53 • 4.6 • 4.7 • 4.18 • 5.9 (a), (b), (h), (i), (j) • 5.22

  32. 5.12.1 Fundamentals of Characters and Strings • Character constant • Integer value represented as character in single quotes • 'z' is integer value of z • 122 in ASCII • String • Series of characters treated as single unit • Can include letters, digits, special characters +, -, * ... • String literal (string constants) • Enclosed in double quotes, for example: "I like C++" • Array of characters, ends with null character '\0' • String is constant pointer • Pointer to string’s first character • Like arrays

  33. 5.12.1 Fundamentals of Characters and Strings • 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” somewhere in memory • Alternative for character array • char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };

  34. 5.12.1 Fundamentals of Characters and Strings • Reading strings • Assign input to character array word[ 20 ] cin >> word • Reads characters until whitespace or EOF • String could exceed array size cin >> setw( 20 ) >> word; • Reads 19 characters (space reserved for '\0')

  35. 5.12.1 Fundamentals of Characters and Strings • cin.getline • Read line of text • cin.getline( array, size, delimiter ); • Copies input into specified array until either • One less than size is reached • delimiter character is input • Example char sentence[ 80 ]; cin.getline( sentence, 80, '\n' );

  36. 5.12.2 String Manipulation Functions of the String-handling Library • String handling library <cstring> provides functions to • Manipulate string data • Compare strings • Search strings for characters and other strings • Tokenize strings (separate strings into logical pieces)

  37. 5.12.2 String Manipulation Functions of the String-handling Library

  38. 12 char x[] = "Happy Birthday to You"; 13 char y[ 25 ]; 14 char z[ 15 ]; 16 strcpy( y, x ); // copy contents of x into y 22 strncpy( z, x, 14 ); // does not copy null character 23 z[ 14 ] = '\0'; // append '\0' to z's contents fig05_28.cpp(1 of 2) The string in array x is: Happy Birthday to You The string in array y is: Happy Birthday to You The string in array z is: Happy Birthday

  39. 12 char s1[ 20 ] = "Happy "; 13 char s2[] = "New Year "; 14 char s3[ 40 ] = ""; 18 strcat( s1, s2 ); // concatenate s2 to s1 24 strncat( s3, s1, 6 ); // places '\0' after last character 29 strcat( s3, s1 ); // concatenate s1 to s3 fig05_29.cpp(1 of 2) s1 = Happy s2 = New Year After strcat(s1, s2): s1 = Happy New Year s2 = New Year After strncat(s3, s1, 6): s1 = Happy New Year s3 = Happy After strcat(s3, s1): s1 = Happy New Year s3 = Happy Happy New Year

  40. 5.12.2 String Manipulation Functions of the String-handling Library

  41. 16 char *s1 = "Happy New Year"; 17 char *s2 = "Happy New Year"; 18 char *s3 = "Happy Holidays"; 22 strcmp( s1, s2 ); 24 strcmp( s1, s3 ); 25 strcmp( s3, s1 ); 28 strncmp( s1, s3, 6 ); 29 strncmp( s1, s3, 7 ); 31 strncmp( s3, s1, 7 ); fig05_30.cpp(1 of 2) s1 = Happy New Year s2 = Happy New Year s3 = Happy Holidays strcmp(s1, s2) = 0 strcmp(s1, s3) = 1 strcmp(s3, s1) = -1 strncmp(s1, s3, 6) = 0 strncmp(s1, s3, 7) = 1 strncmp(s3, s1, 7) = -1

  42. 12 char *string1 = "abcdefghijklmnopqrstuvwxyz"; 13 char *string2 = "four"; 14 char *string3 = "Boston"; 17 strlen( string1 ); 19 strlen( string2 ); 21 strlen( string3 ); fig05_32.cpp(1 of 1) The length of "abcdefghijklmnopqrstuvwxyz" is 26 The length of "four" is 4 The length of "Boston" is 6

  43. 18.9 Character-Handling Library • Character Handling Library • <cctype> • Functions to perform tests and manipulations on characters • Pass character as argument • Character represented by an int • char does not allow negative values • Characters often manipulated as ints • EOF usually has value -1

  44. 18.9 Character-Handling Library

  45. 18.9 Character-Handling Library

  46. 1 // Fig. 18.17: fig18_17.cpp 13 << ( isdigit( '8' ) ? "8 is a" : "8 is not a" ) 15 << ( isdigit( '#' ) ? "# is a" : "# is not a" ) 19 << ( isalpha( 'A' ) ? "A is a" : "A is not a" ) 21 << ( isalpha( 'b' ) ? "b is a" : "b is not a" ) 23 << ( isalpha( '&' ) ? "& is a" : "& is not a" ) 25 << ( isalpha( '4' ) ? "4 is a" : "4 is not a" ) 29 << ( isalnum( 'A' ) ? "A is a" : "A is not a" ) 31 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" ) 33 << ( isalnum( '#' ) ? "# is a" : "# is not a" ) 37 << ( isxdigit( 'F' ) ? "F is a" : "F is not a" ) 39 << ( isxdigit( 'J' ) ? "J is a" : "J is not a" ) 41 << ( isxdigit( '7' ) ? "7 is a" : "7 is not a" ) 43 << ( isxdigit( '$' ) ? "$ is a" : "$ is not a" ) 45 << ( isxdigit( 'f' ) ? "f is a" : "f is not a" ) fig18_17.cpp(1 of 2)

  47. According to isdigit: 8 is a digit # is not a digit According to isalpha: A is a letter b is a letter & is not a letter 4 is not a letter According to isalnum: A is a digit or a letter 8 is a digit or a letter # is not a digit or a letter According to isxdigit: F is a hexadecimal digit J is not a hexadecimal digit 7 is a hexadecimal digit $ is not a hexadecimal digit f is a hexadecimal digit fig18_17.cppoutput (1 of 1)

  48. 13 << ( islower( 'p' ) ? "p is a" : "p is not a" ) 15 << ( islower( 'P' ) ? "P is a" : "P is not a" ) 17 << ( islower( '5' ) ? "5 is a" : "5 is not a" ) 19 << ( islower( '!' ) ? "! is a" : "! is not a" ) 23 << ( isupper( 'D' ) ? "D is an" : "D is not an" ) 25 << ( isupper( 'd' ) ? "d is an" : "d is not an" ) 27 << ( isupper( '8' ) ? "8 is an" : "8 is not an" ) 29 << ( isupper( '$' ) ? "$ is an" : "$ is not an" ) 33 << static_cast< char >( toupper( 'u' ) ) 35 << static_cast< char >( toupper( '7' ) ) 37 << static_cast< char >( toupper( '$' ) ) 39 << static_cast< char >( tolower( 'L' ) ) << endl; fig18_18.cpp(1 of 2)

  49. According to islower: p is a lowercase letter P is not a lowercase letter 5 is not a lowercase letter ! is not a lowercase letter According to isupper: D is an uppercase letter d is not an uppercase letter 8 is not an uppercase letter $ is not an uppercase letter u converted to uppercase is U 7 converted to uppercase is 7 $ converted to uppercase is $ L converted to lowercase is l fig18_18.cpp(2 of 2)

  50. 13 << ( isspace( '\n' ) ? "is a" : "is not a" ) 15 << ( isspace( '\t' ) ? "is a" : "is not a" ) 17 << ( isspace( '%' ) ? "% is a" : "% is not a" ) 21 << ( iscntrl( '\n' ) ? "is a" : "is not a" ) 23 << ( iscntrl( '$' ) ? "$ is a" : "$ is not a" ) 27 << ( ispunct( ';' ) ? "; is a" : "; is not a" ) 29 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" ) 31 << ( ispunct( '#' ) ? "# is a" : "# is not a" ) 35 << ( isprint( '$' ) ? "$ is a" : "$ is not a" ) 37 << ( isprint( '\a' ) ? "is a" : "is not a" ) 41 << ( isgraph( 'Q' ) ? "Q is a" : "Q is not a" ) 43 << ( isgraph( ' ' ) ? "is a" : "is not a" ) fig18_19.cpp(1 of 2)

More Related