5 5 Using const with Pointers const qualifier

  • Slides: 62
Download presentation
5. 5 Using const with Pointers • const qualifier – Value of variable should

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 – 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 // Fig. 5. 10: fig 05_10. cpp // Converting lowercase

1 2 3 4 // Fig. 5. 10: fig 05_10. cpp // Converting lowercase letters to uppercase letters // using a non-constant pointer to non-constant data. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 #include <cctype> 10 11 void convert. To. Uppercase( char * ); 12 13 14 15 int main() { char phrase[] = "characters and $32. 98"; // prototypes for fig 05_10. cpp (1 of 2) Parameter is nonconstant pointer to nonconstant data islower and toupper convert. To. Uppercase modifies variable phrase 16 17 18 19 20 cout << "The phrase before conversion is: " << phrase; convert. To. Uppercase( phrase ); cout << "n. The phrase after conversion is: " << phrase << endl; 21 22 return 0; 23 24 Outline // indicates successful termination } // end main 25 2003 Prentice Hall, Inc. All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 The

26 27 28 29 30 31 32 33 34 35 36 37 38 The // convert string to uppercase letters void convert. To. Uppercase( char *s. Ptr ) { while ( *s. Ptr != '' ) { // current character is not '' Outline fig 05_10. cpp Parameter s. Ptr nonconstant (2 of 2) ispointer to nonconstant data lowercase, if ( islower( *s. Ptr ) ) // if character *s. Ptr = toupper( *s. Ptr ); // convert to uppercase ++s. Ptr; // move } // end while Function islower returns s. Ptrtrue if character is to next character in string lowercase fig 05_10. cpp output (1 of 1) Function toupper returns } // end function convert. To. Uppercase corresponding uppercase When operator ++ applied to character if original character pointer that points to array, 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. 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 // Fig. 5. 11: fig 05_11. cpp // Printing a

1 2 3 4 // Fig. 5. 11: fig 05_11. cpp // Printing a string one character at a time using // a non-constant pointer to constant data. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 void print. Characters( const char * ); 10 11 12 13 int main() { Pass pointer phrase to char phrase[] = "print characters of a string" ; 14 15 16 17 cout << "The string is: n"; print. Characters( phrase ); cout << endl; 18 19 return 0; 20 21 Parameter is nonconstant pointer to constant data. Outline fig 05_11. cpp (1 of 2) function print. Characters. // indicates successful termination } // end main 22 2003 Prentice Hall, Inc. All rights reserved.

23 24 25 26 27 28 29 30 // s. Ptr cannot modify the

23 24 25 26 27 28 29 30 // s. Ptr cannot modify the character to which it points, // i. e. , s. Ptr is a "read-only" pointer void print. Characters( const char *s. Ptr ) { for ( ; *s. Ptr != ''; s. Ptr++ ) // no initialization s. Ptr is nonconstant pointer cout << *s. Ptr; } // end function print. Characters The string is: print characters of a string to constant data; cannot modify character to which s. Ptr points. Increment s. Ptr to point to next character. Outline fig 05_11. cpp (2 of 2) fig 05_11. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 12: fig 05_12. cpp // Attempting to modify

1 2 3 // Fig. 5. 12: fig 05_12. cpp // Attempting to modify data through a // non-constant pointer to constant data. 4 5 void f( const int * ); 6 7 8 9 int main() { int y; Outline fig 05_12. cpp (1 of 1) // prototype Parameter is nonconstant pointer to constant data. 10 11 f( &y ); // f attempts illegal modification 12 13 return 0; // indicates successful termination fig 05_12. cpp output (1 of 1) Pass address of int variable y to attempt illegal modification. 14 15 } // end main 16 17 18 19 20 21 // x. Ptr cannot modify the value of the variable Attempt to modify const // to which it points object pointed to by x. Ptr. void f( const int *x. Ptr ) { *x. Ptr = 100; // error: cannot modify a const object 22 23 } // end function f Error produced when attempting to compile. d: cpphtp 4_examplesch 05Fig 05_12. cpp(21) : error C 2166: l-value specifies const object 2003 Prentice Hall, Inc. All rights reserved.

5. 5 Using const with Pointers • const pointers – Always point to same

5. 5 Using const with Pointers • const pointers – Always point to same memory location – Default for array name (!) – Must be initialized when declared 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 13: fig 05_13. cpp // Attempting to modify

1 2 3 // Fig. 5. 13: fig 05_13. cpp // Attempting to modify a constant pointer to // non-constant data. 4 5 6 7 int main() { int x, y; fig 05_13. cpp (1 of 1) 8 9 10 11 12 ptr is constant pointer to // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the integer. Can modify x (pointed to by // same memory location. ptr) since x not constant. Cannot modify ptr to point * const ptr = &x; 13 14 15 *ptr = 7; ptr = &y; // allowed: // error: ptr is const; cannot assign new address 16 17 return 0; // indicates successful 18 19 } // end main Outline fig 05_13. cpp output (1 of 1) to new address since ptr is constant. *ptr is not const Line 15 generates compiler error by attempting to assign termination new address to constant pointer. d: cpphtp 4_examplesch 05Fig 05_13. cpp(15) : error C 2166: l-value specifies const object 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 14: fig 05_14. cpp // Attempting to modify

1 2 3 // Fig. 5. 14: fig 05_14. cpp // Attempting to modify a constant pointer to constant data. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 int main() { int x = 5, y; fig 05_14. cpp (1 of 1) 11 12 13 14 15 16 17 cout << *ptr << endl; 18 19 20 *ptr = 7; ptr = &y; // error: *ptr value // error: ptr is const; cannot assign new address 21 22 return 0; // indicates successful termination 23 24 Outline ptr is constant pointer to // ptr is a constant pointer to a constant integer constant. // ptr always points to the same location; the integer // at that location cannot be modified. const int *const ptr = &x; Cannot modify x (pointed to by ptr) since *ptr declared Cannot modify ptr to point constant. to new address since ptr is is const; cannot assign new constant. } // end main 2003 Prentice Hall, Inc. All rights reserved.

d: cpphtp 4_examplesch 05Fig 05_14. cpp(19) : error C 2166: l-value specifies const object

d: cpphtp 4_examplesch 05Fig 05_14. cpp(19) : error C 2166: l-value specifies const object d: cpphtp 4_examplesch 05Fig 05_14. cpp(20) : error C 2166: l-value specifies const object Outline fig 05_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. 2003 Prentice Hall, Inc. All rights reserved.

5. 7 Pointer Expressions and Pointer Arithmetic • Pointer arithmetic – – Increment/decrement pointer

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 – v. Ptr points to first element v[ 0 ], which is at location 3000 v. Ptr = 3000 location – v. Ptr += 2; sets v. Ptr to 3008 v. Ptr points to v[ 2 ] 3000 3004 v[0] v[1] pointer variable v. Ptr 2003 Prentice Hall, Inc. All rights reserved. 3008 3012 v[2] 3016 v[3] v[4]

5. 7 Pointer Expressions and Pointer Arithmetic • Subtracting pointers – Returns number of

5. 7 Pointer Expressions and Pointer Arithmetic • Subtracting pointers – Returns number of elements between two addresses v. Ptr 2 = &v[ 2 ]; v. Ptr = &v[ 0 ]; v. Ptr 2 - v. Ptr == 2 • 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.

5. 7 Pointer Expressions and Pointer Arithmetic • Pointer comparison – Use equality and

5. 7 Pointer Expressions and Pointer Arithmetic • Pointer comparison – Use equality and relational operators – Comparisons meaningless unless pointers point to members of same array – Compare addresses stored in pointers – Example: could show that one pointer points to higher numbered element of array than other pointer – Common use to determine whether pointer is 0 (does not point to anything) 2003 Prentice Hall, Inc. All rights reserved.

5. 8 Relationship Between Pointers and Arrays • Arrays and pointers closely related –

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 *( b. Ptr + n ) • Called pointer/offset notation – Addresses • &b[ 3 ] same as b. Ptr + 3 – Array name can be treated as pointer • b[ 3 ] same as *( b + 3 ) – Pointers can be subscripted (pointer/subscript notation) • b. Ptr[ 3 ] same as b[ 3 ] 2003 Prentice Hall, Inc. All rights reserved.

1 2 // Fig. 5. 20: fig 05_20. cpp // Using subscripting and pointer

1 2 // Fig. 5. 20: fig 05_20. cpp // Using subscripting and pointer notations with arrays. 3 4 #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 11 12 int main() { int b[] = { 10, 20, 30, 40 }; int *b. Ptr = b; // set b. Ptr to point to array b 13 14 15 16 // output array b using array subscript notation cout << "Array b printed with: n" << "Array subscript notationn" ; 17 18 19 for ( int i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << 'n'; 20 21 22 23 24 // output array b using the array name and // pointer/offset notation cout << "n. Pointer/offset notation where " << "the pointer is the array namen" ; Outline fig 05_20. cpp (1 of 2) Using array subscript notation. 25 2003 Prentice Hall, Inc. All rights reserved.

26 27 28 for ( int offset 1 = 0; offset 1 < 4;

26 27 28 for ( int offset 1 = 0; offset 1 < 4; offset 1++ ) cout << "*(b + " << offset 1 << ") = " << *( b + offset 1 ) << 'n'; 29 30 31 // output array b using b. Ptr and array subscript notation Using array name and cout << "n. Pointer subscript notationn" ; 32 33 34 for ( int j = 0; j < 4; j++ ) cout << "b. Ptr[" << j << "] = " << b. Ptr[ j ] << 'n'; 35 36 cout << "n. Pointer/offset notationn" ; 37 38 39 40 41 // output array b using b. Ptr and pointer/offset notation for ( int offset 2 = 0; offset 2 < 4; offset 2++ ) cout << "*(b. Ptr + " << offset 2 << ") = " << *( b. Ptr + offset 2 ) << 'n'; 42 43 return 0; 44 45 Outline pointer/offset notation. } // end main fig 05_20. cpp (2 of 2) Using pointer subscript notation. // indicates successful termination Using b. Ptr and pointer/offset notation. 2003 Prentice Hall, Inc. All rights reserved.

Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2]

Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40 Outline fig 05_20. cpp output (1 of 1) Pointer/offset notation where the pointer is the array name *(b + 0) = 10 *(b + 1) = 20 *(b + 2) = 30 *(b + 3) = 40 Pointer b. Ptr[0] b. Ptr[1] b. Ptr[2] b. Ptr[3] subscript notation = 10 = 20 = 30 = 40 Pointer/offset notation *(b. Ptr + 0) = 10 *(b. Ptr + 1) = 20 *(b. Ptr + 2) = 30 *(b. Ptr + 3) = 40 2003 Prentice Hall, Inc. All rights reserved.

5. 11 Function Pointers • Pointers to functions – Contain address of function –

5. 11 Function Pointers • Pointers to functions – Contain address of function – Similar to how array name is address of first element – Function name is starting address of code that defines function • Function pointers can be – – Passed to functions Returned from functions Stored in arrays Assigned to other function pointers 2003 Prentice Hall, Inc. All rights reserved.

5. 11 Function Pointers • Calling functions using pointers – Assume parameter: • bool

5. 11 Function Pointers • Calling functions using pointers – Assume parameter: • bool ( *compare ) ( int, int ) – Execute function with either • ( *compare ) ( int 1, int 2 ) – Dereference pointer to function to execute OR • compare( int 1, int 2 ) – Could be confusing • User may think compare name of actual function in program 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 25: fig 05_25. cpp // Multipurpose sorting program

1 2 3 // Fig. 5. 25: fig 05_25. cpp // Multipurpose sorting program using function pointers. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 #include <iomanip> 10 11 using std: : setw; 12 13 14 15 16 17 // prototypes void bubble( int [], const int, bool (*)( int, int ) ); void swap( int * const, int * const ); bool ascending( int, int ); bool descending( int, int ); 18 19 20 21 22 23 24 int main() { const int array. Size = 10; int order; int counter; int a[ array. Size ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; Outline fig 05_25. cpp (1 of 5) Parameter is pointer to function that receives two integer parameters and returns bool result. 25 2003 Prentice Hall, Inc. All rights reserved.

26 27 28 29 30 31 32 33 cout << "Enter 1 to sort

26 27 28 29 30 31 32 33 cout << "Enter 1 to sort in ascending order, n" << "Enter 2 to sort in descending order: " ; cin >> order; cout << "n. Data items in original ordern" ; // output original array for ( counter = 0; counter < array. Size; counter++ ) cout << setw( 4 ) << a[ counter ]; 34 35 36 37 38 39 40 // sort array in ascending order; pass function ascending // as an argument to specify ascending sorting order if ( order == 1 ) { bubble( a, array. Size, ascending ); cout << "n. Data items in ascending ordern" ; } 41 42 43 44 45 46 47 // sort array in descending order; pass function descending // as an agrument to specify descending sorting order else { bubble( a, array. Size, descending ); cout << "n. Data items in descending ordern" ; } Outline fig 05_25. cpp (2 of 5) 48 2003 Prentice Hall, Inc. All rights reserved.

49 50 51 // output sorted array for ( counter = 0; counter <

49 50 51 // output sorted array for ( counter = 0; counter < array. Size; counter++ ) cout << setw( 4 ) << a[ counter ]; 52 53 cout << endl; 54 55 return 0; fig 05_25. cpp (3 of 5) // indicates successful termination 56 57 } // end main 58 59 60 61 62 63 64 65 // multipurpose bubble sort; parameter compare is a pointer to function that receives two // the comparison function that determines 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++ ) 66 67 68 69 70 71 72 Outline compare is pointer to indicate pointer to function // loop to control number of comparisons per pass Call passed function for ( int count = 0; count < size - 1; count++ ) compare; dereference pointer to execute function. out of order, swap them // if adjacent elements are if ( (*compare)( work[ count ], work[ count + 1 ] ) ) swap( &work[ count ], &work[ count + 1 ] ); 2003 Prentice Hall, Inc. All rights reserved.

73 74 } // end function bubble 75 76 77 78 79 80 81

73 74 } // end function bubble 75 76 77 78 79 80 81 82 // swap values at memory locations to which // element 1 Ptr and element 2 Ptr point void swap( int * const element 1 Ptr, int * const element 2 Ptr ) { int hold = *element 1 Ptr; *element 1 Ptr = *element 2 Ptr; *element 2 Ptr = hold; 83 84 } // end function swap 85 86 87 88 89 90 91 92 Outline fig 05_25. cpp (4 of 5) // 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 93 2003 Prentice Hall, Inc. All rights reserved.

94 95 96 97 98 99 100 // determine whether elements are out of

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 Enter 1 to Enter 2 to Data items 2 6 Data items 2 4 fig 05_25. cpp (5 of 5) fig 05_25. cpp output (1 of 1) sort in ascending order, sort in descending order: 1 in original order 4 8 10 12 89 68 in ascending order 6 8 10 12 37 45 Outline 45 37 68 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 37 4 2 2003 Prentice Hall, Inc. All rights reserved.

5. 11 Function Pointers • Arrays of pointers to functions – Menu driven systems

5. 11 Function Pointers • Arrays of pointers to functions – Menu driven systems – Pointers to each function stored in array of pointers to functions • All functions must have same return type and same parameter types – Menu choice subscript into array of function pointers 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 26: fig 05_26. cpp // Demonstrating an array

1 2 3 // Fig. 5. 26: fig 05_26. cpp // Demonstrating an array of pointers to functions. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 // function prototypes void function 1( int ); void function 2( int ); void function 3( int ); 13 14 15 16 17 18 int main() Array initialized with names { of three functions; function // initialize array of 3 pointers to functions that each names are pointers. // take an int argument and return void (*f[ 3 ])( int ) = { function 1, function 2, function 3 }; 19 20 int choice; 21 22 23 cout << "Enter a number between 0 and 2, 3 to end: " ; cin >> choice; Outline fig 05_26. cpp (1 of 3) 24 2003 Prentice Hall, Inc. All rights reserved.

25 26 // process user's choice while ( choice >= 0 && choice <

25 26 // process user's choice while ( choice >= 0 && choice < 3 ) { 27 28 29 30 // invoke function at location choice in array f // and pass choice as an argument (*f[ choice ])( choice ); 31 32 33 34 } 35 36 cout << "Program execution 37 38 return 0; Outline fig 05_26. cpp (2 of 3) cout << "Enter a number between 0 and 2, 3 to end: " ; cin >> choice; Call chosen function by dereferencing corresponding completed. " << endl; element in array. // indicates successful termination 39 40 } // end main 41 42 43 44 45 void function 1( int a ) { cout << "You entered " << a << " so function 1 was callednn" ; 46 47 } // end function 1 48 2003 Prentice Hall, Inc. All rights reserved.

49 50 51 52 void function 2( int b ) { cout << "You

49 50 51 52 void function 2( int b ) { cout << "You entered " << b << " so function 2 was callednn" ; 53 54 } // end function 2 55 56 57 58 59 void function 3( int c ) { cout << "You entered " << c << " so function 3 was callednn" ; 60 61 } // end function 3 Outline fig 05_26. cpp (3 of 3) fig 05_26. cpp output (1 of 1) Enter a number between 0 and 2, 3 to end: 0 You entered 0 so function 1 was called Enter a number between 0 and 2, 3 to end: 1 You entered 1 so function 2 was called Enter a number between 0 and 2, 3 to end: 2 You entered 2 so function 3 was called Enter a number between 0 and 2, 3 to end: 3 Program execution completed. 2003 Prentice Hall, Inc. All rights reserved.

Memory It is the job of the Operating System to • Manage the allocation

Memory It is the job of the Operating System to • Manage the allocation of memory to processes • Keep track of what memory/addresses each process is allowed to access • Reserve portion of memory for use by the OS • Enforce protection of memory space of each process 2003 Prentice Hall, Inc. All rights reserved.

 • Pointer – a variable whose value is a memory address • Pointee

• Pointer – a variable whose value is a memory address • Pointee – the value in memory whose address is stored in a pointer – the pointee is the target of the pointer. • A pointer may or may not have a target. Pointers without targets should be set to 0 or NULL. 2003 Prentice Hall, Inc. All rights reserved.

int x = 4, y = 99; int *p 1, *p 2; p 1

int x = 4, y = 99; int *p 1, *p 2; p 1 = &x; p 2 = &y; *p 1 = 3; cout << *p 1 << “ “<< *p 2; p 2 = p 1; cout << *p 1 << “ “<< *p 2; 2003 Prentice Hall, Inc. All rights reserved.

float i, x, *p, *q; p = &i; *p = 10. 0; q =

float i, x, *p, *q; p = &i; *p = 10. 0; q = &x; *q = 8. 6; cout << x << endl; cout << I << endl; *p = 9. 5; p = q; q = &i; cout << *p <<endl; cout << i <<endl; cout << x << endl; cout << *q << endl; 2003 Prentice Hall, Inc. All rights reserved.

int *p, *q, *r, *s; int a, b, c, d[10]; p = &a; q

int *p, *q, *r, *s; int a, b, c, d[10]; p = &a; q = &b; *q = 98; *p = 76; q = p; cout <<*p << endl; cout << *q << endl; r = &d[0]; //note this is the same as saying r=d, which is also valid for (int i =0; i < 10; i++) r[i] = i; p = r; ++p; s= p; ++s; cout << *r << endl; cout << *q << endl; cout << *p <<endl; cout << *s <<endl; 2003 Prentice Hall, Inc. All rights reserved.

Dynamic Allocation Using the new command: int *p 1 = new int; double *p

Dynamic Allocation Using the new command: int *p 1 = new int; double *p 2 = new double[1000]; for (i = 0; i < 1000; i++) p 2[i] = 2*i; delete p 1; delete [] p 2; 2003 Prentice Hall, Inc. All rights reserved.

int *p, *q, *r, *s; p = new int; *p = 76; cout <<*p

int *p, *q, *r, *s; p = new int; *p = 76; cout <<*p << endl; r = new int [10]; //note this is the same as saying r=d, which is also valid for (int i =0; i < 10; i++) r[i] = i; q = r; ++q; s= q; ++s; cout << *r << endl; cout << *q << endl; cout << *p <<endl; cout << *s <<endl; 2003 Prentice Hall, Inc. All rights reserved.

Memory Leak int *p 1 = new int; double *p 2 = new double[1000];

Memory Leak int *p 1 = new int; double *p 2 = new double[1000]; for (i = 0; i < 1000; i++) p 2[i] = 2*i; p 2 = p 1; //NOW THE ARRAY IS LOST delete p 1; delete [] p 2; 2003 Prentice Hall, Inc. All rights reserved.

Array Resizing 2003 Prentice Hall, Inc. All rights reserved.

Array Resizing 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 1 Fundamentals of Characters and Strings • Character constant – Integer value

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 '' – String is constant pointer • Pointer to string’s first character – Like arrays 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 1 Fundamentals of Characters and Strings • String assignment – Character array

5. 12. 1 Fundamentals of Characters and Strings • String assignment – Character array • char color[] = "blue"; – Creates 5 element char array color • last element is '' – Variable of type char * • char *color. Ptr = "blue"; – Creates pointer color. Ptr to letter b in string “blue” • “blue” somewhere in memory – Alternative for character array • char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘’ }; 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 1 Fundamentals of Characters and Strings • Reading strings – Assign input

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 '') 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 1 Fundamentals of Characters and Strings • cin. getline – Read line

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' ); 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • String handling library

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) 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library char *strcpy( char *s

5. 12. 2 String Manipulation Functions of the String-handling Library char *strcpy( char *s 1, const char *s 2 ); Copies the string s 2 into the character array s 1. The value of s 1 is returned. char *strncpy( char *s 1, const char *s 2, size_t n ); Copies at most n characters of the string s 2 into the character array s 1. The value of s 1 is returned. char *strcat( char *s 1, const char *s 2 ); Appends the string s 2 to the string s 1. The first character of s 2 overwrites the terminating null character of s 1. The value of s 1 is returned. char *strncat( char *s 1, const char *s 2, size_t n ); Appends at most n characters of string s 2 to string s 1. The first character of s 2 overwrites the terminating null character of s 1. The value of s 1 is returned. int strcmp( const char *s 1, const char *s 2 ); Compares the string s 1 with the string s 2. The function returns a value of zero, less than zero or greater than zero if s 1 is equal to, less than or greater than s 2, respectively. 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library int strncmp( const char

5. 12. 2 String Manipulation Functions of the String-handling Library int strncmp( const char *s 1, const char *s 2, size_t n ); Compares up to n characters of the string s 1 with the string s 2. The function returns zero, less than zero or greater than zero if s 1 is equal to, less than or greater than s 2, respectively. char *strtok( char *s 1, const char *s 2 ); A sequence of calls to strtok breaks string s 1 into “tokens”—logical pieces such as words in a line of text—delimited by characters contained in string s 2. The first call contains s 1 as the first argument, and subsequent calls to continue tokenizing the same string contain NULL as the first argument. A pointer to the current to ken is returned by each call. If there are no more tokens when the function is called, NULL is returned. size_t strlen( const char *s ); Determines the length of string s. The number of characters preceding the terminating null character is returned. 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Copying strings –

5. 12. 2 String Manipulation Functions of the String-handling Library • Copying strings – char *strcpy( char *s 1, const char *s 2 ) • Copies second argument into first argument – First argument must be large enough to store string and terminating null character – char *strncpy( char *s 1, const char *s 2, size_t n ) • Specifies number of characters to be copied from string into array • Does not necessarily copy terminating null character 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 28: fig 05_28. cpp // Using strcpy and

1 2 3 // Fig. 5. 28: fig 05_28. cpp // Using strcpy and strncpy. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <cstring> 9 10 11 12 13 14 int main() { char x[] = "Happy Birthday to You"; Copy entire string in array x char y[ 25 ]; into array y. char z[ 15 ]; 15 16 17 18 19 20 21 22 23 24 25 strcpy( y, x ); Outline <cstring> contains prototypes for strcpy and strncpy. fig 05_28. cpp (1 of 2) // prototypes for strcpy and strncpy // copy contents of x into y cout << "The string in array x is: " << x << "n. The string in array y is: " Copy first 14 characters of << y << 'n'; array x into array y. Note that Append terminating null // copy first 14 characters of x into zthis does not write terminating character. strncpy( z, x, 14 ); // does not copy null character z[ 14 ] = ''; // append '' to z's contents cout << "The string in array z is: " << z << endl; 2003 Prentice Hall, Inc. All rights reserved.

26 27 28 29 return 0; // indicates successful termination } // end main

26 27 28 29 return 0; // indicates successful termination } // end main 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 Outline String to copy. Copied string using strcpy. fig 05_28. cpp Copied first 14 characters (2 of 2) using strncpy. fig 05_28. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Concatenating strings –

5. 12. 2 String Manipulation Functions of the String-handling Library • Concatenating strings – char *strcat( char *s 1, const char *s 2 ) • Appends second argument to first argument • First character of second argument replaces null character terminating first argument • Ensure first argument large enough to store concatenated result and null character – char *strncat( char *s 1, const char *s 2, size_t n ) • Appends specified number of characters from second argument to first argument • Appends terminating null character to result 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 29: fig 05_29. cpp // Using strcat and

1 2 3 // Fig. 5. 29: fig 05_29. cpp // Using strcat and strncat. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <cstring> 9 10 11 12 13 14 int main() { char s 1[ 20 ] = "Happy "; char s 2[] = "New Year "; char s 3[ 40 ] = ""; Outline <cstring> contains prototypes for strcat and strncat. fig 05_29. cpp (1 of 2) // prototypes for strcat and strncat Append s 2 to s 1. 15 16 cout << "s 1 = " << s 1 << "ns 2 = " << s 2; 17 18 strcat( s 1, s 2 ); 19 20 21 cout << "nn. After strcat(s 1, s 2): ns 1 = " << s 1 Append first 6 characters of << "ns 2 = " << s 2; 22 23 24 // concatenate first 6 characters of s 1 to s 3 strncat( s 3, s 1, 6 ); // places '' after last character // concatenate s 2 to s 1 to s 3. 25 2003 Prentice Hall, Inc. All rights reserved.

26 27 cout << "nn. After strncat(s 3, s 1, 6): ns 1 =

26 27 cout << "nn. After strncat(s 3, s 1, 6): ns 1 = " << s 1 Append s 1 to s 3. << "ns 3 = " << s 3; 28 29 30 31 strcat( s 3, s 1 ); // concatenate s 1 to s 3 cout << "nn. After strcat(s 3, s 1): ns 1 = " << s 1 << "ns 3 = " << s 3 << endl; fig 05_29. cpp (2 of 2) 32 33 return 0; fig 05_29. cpp output (1 of 1) 34 35 // indicates successful termination Outline } // end main s 1 = Happy s 2 = New Year After strcat(s 1, s 2): s 1 = Happy New Year s 2 = New Year After strncat(s 3, s 1, 6): s 1 = Happy New Year s 3 = Happy After strcat(s 3, s 1): s 1 = Happy New Year s 3 = Happy New Year 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Comparing strings –

5. 12. 2 String Manipulation Functions of the String-handling Library • Comparing strings – Characters represented as numeric codes • Strings compared using numeric codes – Character codes / character sets • ASCII – “American Standard Code for Information Interchage” • EBCDIC – “Extended Binary Coded Decimal Interchange Code” 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Comparing strings –

5. 12. 2 String Manipulation Functions of the String-handling Library • Comparing strings – int strcmp( const char *s 1, const char *s 2 ) • Compares character by character • Returns – Zero if strings equal – Negative value if first string less than second string – Positive value if first string greater than second string – int strncmp( const char *s 1, const char *s 2, size_t n ) • Compares up to specified number of characters • Stops comparing if reaches null character in one of arguments 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 30: fig 05_30. cpp // Using strcmp and

1 2 3 // Fig. 5. 30: fig 05_30. cpp // Using strcmp and strncmp. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 #include <cstring> 13 14 15 16 17 18 19 20 21 22 23 24 25 fig 05_30. cpp (1 of 2) <cstring> contains prototypes for strcmp and strncmp. // prototypes for strcmp and strncmp int main() { char *s 1 = "Happy New Year"; char *s 2 = "Happy New Year"; char *s 3 = "Happy Holidays"; cout << << << Outline Compare s 1 and s 2. "s 1 = " << s 1 << "ns 2 = " << s 2 Compare s 1 and s 3. "ns 3 = " << s 3 << "nnstrcmp(s 1, s 2) = " setw( 2 ) << strcmp( s 1, s 2 ) Compare s 3 and s 1. "nstrcmp(s 1, s 3) = " << setw( 2 ) strcmp( s 1, s 3 ) << "nstrcmp(s 3, s 1) = " setw( 2 ) << strcmp( s 3, s 1 ); 2003 Prentice Hall, Inc. All rights reserved.

Compare up to 6 characters of Outline Compare up to 7 characters of "nnstrncmp(s

Compare up to 6 characters of Outline Compare up to 7 characters of "nnstrncmp(s 1, s 3, 6) = " <<s 1 and s 3. setw( 2 ) s 1 and s 3. strncmp( s 1, s 3, 6 ) << "nstrncmp(s 1, s 3, 7) = " Compare up to 7 characters of setw( 2 ) << strncmp( s 1, s 3, 7 ) fig 05_30. cpp s 3 and s 1. "nstrncmp(s 3, s 1, 7) = " (2 of 2) setw( 2 ) << strncmp( s 3, s 1, 7 ) << endl; 26 27 28 29 30 31 cout << << << 32 33 return 0; 34 35 // indicates successful termination fig 05_30. cpp output (1 of 1) } // end main s 1 = Happy New Year s 2 = Happy New Year s 3 = Happy Holidays strcmp(s 1, s 2) = 0 strcmp(s 1, s 3) = 1 strcmp(s 3, s 1) = -1 strncmp(s 1, s 3, 6) = 0 strncmp(s 1, s 3, 7) = 1 strncmp(s 3, s 1, 7) = -1 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Tokenizing – Breaking

5. 12. 2 String Manipulation Functions of the String-handling Library • Tokenizing – Breaking strings into tokens, separated by delimiting characters – Tokens usually logical units, such as words (separated by spaces) – "This is my string" has 4 word tokens (separated by spaces) – char *strtok( char *s 1, const char *s 2 ) • Multiple calls required – First call contains two arguments, string to be tokenized and string containing delimiting characters • Finds next delimiting character and replaces with null character – Subsequent calls continue tokenizing • Call with first argument NULL 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 31: fig 05_31. cpp // Using strtok. #include

1 2 3 // Fig. 5. 31: fig 05_31. cpp // Using strtok. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <cstring> 9 10 11 12 13 int main() { char sentence[] = "This is a sentence with 7 tokens" ; char *token. Ptr; Outline <cstring> contains prototype for strtok. fig 05_31. cpp (1 of 2) // prototype for strtok 14 15 16 cout << "The string to be tokenized is: n" << sentence << "nn. The tokens are: nn"First call to strtok begins ; 17 18 19 // begin tokenization of sentence token. Ptr = strtok( sentence, " " ); tokenization. 2003 Prentice Hall, Inc. All rights reserved.

21 22 23 24 // continue tokenizing sentence until token. Ptr becomes NULL while

21 22 23 24 // continue tokenizing sentence until token. Ptr becomes NULL while ( token. Ptr != NULL ) { cout << token. Ptr << 'n'; token. Ptr = strtok( NULL, " " ); // get next token 25 26 } // end while 27 28 cout << "n. After strtok, sentence = " << sentence << endl; 29 30 return 0; 31 32 // indicates successful Outline fig 05_31. cpp (2 of 2) Subsequent calls to strtok with NULL as first argument to indicate continuation. termination } // end main 2003 Prentice Hall, Inc. All rights reserved.

The string to be tokenized is: This is a sentence with 7 tokens The

The string to be tokenized is: This is a sentence with 7 tokens The tokens are: This is a sentence with 7 tokens Outline fig 05_31. cpp output (1 of 1) After strtok, sentence = This 2003 Prentice Hall, Inc. All rights reserved.

5. 12. 2 String Manipulation Functions of the String-handling Library • Determining string lengths

5. 12. 2 String Manipulation Functions of the String-handling Library • Determining string lengths – size_t strlen( const char *s ) • Returns number of characters in string – Terminating null character not included in length 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 5. 32: fig 05_32. cpp // Using strlen. #include

1 2 3 // Fig. 5. 32: fig 05_32. cpp // Using strlen. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <cstring> 9 10 11 12 13 14 int main() { char *string 1 = "abcdefghijklmnopqrstuvwxyz" ; char *string 2 = "four"; char *string 3 = "Boston"; 15 16 17 18 19 20 21 cout << << << 22 23 return 0; 24 25 Outline <cstring> contains prototype for strlen. fig 05_32. cpp (1 of 1) // prototype for strlen "The length of "" << string 1 "" is " << strlen( string 1 ) "n. The length of "" << string 2 "" is " << strlen( string 2 ) "n. The length of "" << string 3 "" is " << strlen( string 3 ) << endl; Using strlen to determine length of strings. // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved.

The length of "abcdefghijklmnopqrstuvwxyz" is 26 The length of "four" is 4 The length

The length of "abcdefghijklmnopqrstuvwxyz" is 26 The length of "four" is 4 The length of "Boston" is 6 Outline fig 05_32. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved.

Review Pointers and Strings : What does the following code do? void POKEMON(char *PIKACHU,

Review Pointers and Strings : What does the following code do? void POKEMON(char *PIKACHU, char *ASH) { while (*PIKACHU++ == *ASH++) ; return; } IMPLEMENT IT! 2003 Prentice Hall, Inc. All rights reserved.