Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 1 5.1Introduction Pointers –Powerful, but difficult to master.

Similar presentations


Presentation on theme: " 2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 1 5.1Introduction Pointers –Powerful, but difficult to master."— Presentation transcript:

1

2  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 1 5.1Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings –Similar to Reference Use reference operator instead of pointer whenever possible

3  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 2 5.2Pointer Variable Declarations and Initialization Pointer variables –Contain memory addresses as their values –Normal variables contain a specific value (direct reference) –Pointers contain the address of a variable that has a specific value (indirect reference) Indirection –Referencing a pointer value Pointer declarations –* indicates variable is a pointer int *myPtr; declares a pointer to an int, a pointer of type int * –Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; count 7 countPtr count 7

4  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 3 5.2Pointer Variable Declarations and Initialization Can declare pointers to any data type Pointers initialization –Initialized to 0, NULL, or an address 0 or NULL points to nothing

5  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 4 5.3Pointer Operators & (address operator) –Returns the address of its operand –Example int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y –yPtr “points to” y or yPtr contains the address where y is located in memory yPtr y 5 yptr 50000060000 y 5 address of y is value of yptr yPtr = 60000 Memory loc 60000 has 5

6  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 5 5.3Pointer Operators * (indirection/dereferencing operator) –Returns the value of what its operand points to –*yPtr returns y (because yPtr points to y ) –* can be used to assign a value to a location in memory *yptr = 7; // changes y to 7 –Dereferenced pointer (operand of * ) must be an lvalue (no constants) * and & are inverses –Cancel each other out *&myVar == myVar and &*yPtr == yPtr

7  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 6 1. Declare variables 2 Initialize variables 3. Print Program Output on next page 1// Fig. 5.4: fig05_04.cpp 2// Using the & and * operators 3#include 4 5using std::cout; 6using std::endl; 7 8int main() 9{9{ 10 int a; // a is an integer 11 int *aPtr; // aPtr is a pointer to an integer 12 13 a = 7; 14 aPtr = &a; // aPtr set to 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; 25 return 0; 26} The address of a is the value of aPtr. The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a. Notice how * and & are inverses

8  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 7 The address of a is 006AFDF4 The value of aPtr is 006AFDF4 The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 006AFDF4 *&aPtr = 006AFDF4 Summary int a; // declare a variable ‘a’ of type integer, a gets a specific address int *aPtr; // declare a pointer ‘aPtr’ of type inter to an integer aPtr = &a; // Can only assign address to ‘aPtr’, Example, address of ‘a’ *aPtr = 100; // assign a value of 100 to address pointed by aPtr (55000) int b = *aPtr; // Var b now has a value of 100 by aPtr (55000) &b = aPtr; // ERROR, CANNOT CHANGE WHERE B IS LOCATED. b = aPtr; // ERROR, cannot convert from 'int *' to 'int' b = reinterpret_cast (aPtr); The reinterpret_cast operator allows pointer of one type to be converted into a pointer of another type. It also allows any integral type to be converted into any pointer type and vice versa.

9  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 8 Passing Arguments by Reference Except for arrays, by default, C++ passes arguments by value. This can be very inefficient when large data items are passed When data is large, or must be modified by the function, the argument can be passed by reference (address) With Pointers, you must explicitly pass the address to the function and de-reference the argument within the function Using the reference operator is a better way Pass address of argument using & operator –Allows you to change the data at that location in memory –No need to use & with arrays. Array name is already a pointer

10  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 9 Example of Call-by-Reference Reference operator VS Pointer void swap (int *x, int *y); main () { int val1=1, val2=2; swap (&val1, &val2); return ; } void swap (int *x, int *y) { int temp = *x; *x = *y; *y = temp; return ; } void swap (int &x, int &y); main () { int val1=1, val2=2; swap (val1, val2); return ; } void swap (int &x, int &y) { int temp = x; x = y; y = temp; return ; }

11  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 10 Summary - Calling Functions by Reference using pointers Call-by-reference with pointer arguments –Pass address of the argument to the function using & operator int myNum = 3; int *iPtr = &myNum; //iPtr has myNum’s addr NumTimesTwo( &myNum ); (from main) NumTimesTwo( iPtr ); (from main) void NumTimesTwo( int *number ) { *number = 2 * ( *number ); } –use *number to de-reference the pointer in the function

12  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 11 1. Function prototype - takes a pointer to an int. 1.1 Initialize variables 2. Call function 3. Define function Program Output 1// Fig. 5.7: fig05_07.cpp 2// Cube a variable using call-by-reference 3// with a pointer argument 4#include 5 6using std::cout; 7using std::endl; 8 9void cubeByReference( int * ); // prototype 10 11int main() 12{ 13 int number = 5; 14 15 cout << "The original value of number is " << number; 16 cubeByReference( &number ); 17 cout << "\nThe new value of number is " <<number<< endl; 18 return 0; 19} 20 21void cubeByReference( int *nPtr ) 22{ 23 *nPtr = *nPtr * *nPtr * *nPtr; // cube number in main 24} Inside cubeByReference, *nPtr is used ( *nPtr is number ). The original value of number is 5 The new value of number is 125 Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable).

13  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 12 More on Using References A reference is not a pointer ! –It must be assigned a value when defined –It cannot be unassigned or re-assigned int i = 7; // creates i int &j=i; // creates an “independent” reference to i j++; // increments val of i, not the address of i j is an alias of i. If the value of i changes, so does the value of j. You use j just as you would use i. The address of a reference is actually the address of the value associated with the address References can be returned just like any other function return parameters i 7 j i 1000 7 j 1000

14  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 13 #include using namespace std; int main() { int i = 10; int &j = i; int *ip = &i; cout << "i = " << i << ", j= " << j << ", *ip=" << *ip << endl; j++; cout << "i = " << i << ", j= " << j << ", *ip=" << *ip << endl; cout << "&i = " << &i << ", &j= " << &j << ", ip=" << ip << endl; return 0; } i = 10, j= 10, *ip=10 i = 11, j= 11, *ip=11 &i = 0012FF7C, &j= 0012FF7C, ip=0012FF7C Assigning a reference and a pointer to an integer. Note that incrementing j changes the value of i and not the address of i They all point to the same memory location For Address of ip, you do not use &

15  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 14 5.5Using the Const Qualifier with Pointers const qualifier –Variable cannot be changed –const used when function must NOT change a variable –Attempting to change a const variable is a compiler error Four ways to pass a pointer to a function data is constant or pointer is constant, or both non-const pointer to non-const data non-const pointer to const data const pointer to non-const data const pointer to const data

16  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 15 Using the Const Qualifier with Pointers int array j[] = {2,3,6,7,9}; int * const myPtr = j; j and myPtr both have an address as their value and point to the same memory location. They are constant and cannot point to any other address. However, the data they point to, can change. j 2 3 6 7 9 myPtr

17  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 16 5.5Using the Const Qualifier with Pointers Four ways to pass a pointer to a function non-const pointer to non-const data int *myPtr = &j; non-const pointer to const data const int * myPtr = &j; const pointer to non-const data int * const myPtr = &j; const pointer to const data const int *const myPtr = &j;

18  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 17 non-const pointer to non-const data int *myPtr ; int j = 20 ; int *myPtr = &j ; –Highest access granted –Pointer can be modified to point to another data –Data can be modified through the dereferenced pointer –Can be used to receive a string in a function that uses pointer arithmetic to process and possibly modify each char in the string

19  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 18 // Fig. 5.10: fig05_10.cpp // Converting lowercase letters to uppercase letters // using a non-constant pointer to non-constant data #include using namespace std; #include void convertToUppercase( char * ); int main() { char string[] = "characters and $32.98"; cout << "The string before conversion is: " << string; convertToUppercase( string ); cout << "\nThe string after conversion is: " << string << endl; return 0; }

20  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 19 void convertToUppercase( char *sPtr ) { while ( *sPtr != '\0' ) { if ( islower( *sPtr ) ) // convert to uppercase *sPtr = toupper( *sPtr ); ++sPtr; // move sPtr to the next character }

21  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 20 non-const pointer to const data non-const pointers to const data const char *myPtr = &x; Read as: myPtr is a pointer to constant character –Pointer can be modified to point to other data of same type –Data to which this pointer points to cannot be modified by this pointer (*myPtr)++ will result in compiler error myPtr++ OK, myPtr points new memory location

22  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 21 // Fig. 5.11: fig05_11.cpp // Printing a string one character at a time using // a non-constant pointer to constant data #include using namespace std; void printCharacters( const char * ); int main() { char string[] = "print characters of a string"; cout << "The string is:\n"; printCharacters( string ); cout << endl; return 0; } // In printCharacters, sPtr cannot modify the character // to which it points. sPtr is a "read-only" pointer void printCharacters( const char *sPtr ) { for ( ; *sPtr != '\0'; sPtr++ ) // no initialization cout << *sPtr; }

23  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 22 const pointer to non-const data const pointers to non- const data int *const myPtr = &x; Read as: myPtr is a constant pointer to integer data type Always point to the same memory location. If attempt is made to change the address, you get a compiler error Name of an array is a constant pointer. Name of array always point to the first element in the array Must be initialized when declared (*myPtr)++; // OK, just incrementing data *(myPtr++); // NOT OK, incrementing address *myPtr++; // NOT OK, incrementing address ++myPtr; // NOT OK, incrementing address

24  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 23 1. Declare variables 1.1 Declare const pointer to an int. 2. Change *ptr (which is x ). 2.1 Attempt to change ptr. 3. Output Program Output 1// Fig. 5.13: fig05_13.cpp 2// Attempting to modify a constant pointer to 3// non-constant data 4#include 5 6int main() 7{7{ 8 int x, y; 9 10 int * const ptr = &x; // ptr is a constant pointer to an 11 // integer. An integer can be modified 12 // through ptr, but ptr always points 13 // to the same memory location. 14 *ptr = 7; 15 ptr = &y; 16 17 return 0; 18} Error E2024 Fig05_13.cpp 15: Cannot modify a const object in function main() Changing *ptr is allowed - x is not a constant. Changing ptr is an error - ptr is a constant pointer.

25  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 24 const pointer to const data const pointers to const data const int * const myPtr = &x; –Read as: myPtr is a constant pointer to const integer data type –Least amount of privilege is granted in this case –Always point to the same memory location. If attempt is made to change the address, you get a compiler error –Data to which this pointer points to cannot be modified by this pointer Name of an array is a constant pointer. Name of array always point to the first element in the array Must be initialized when declared (*myPtr)++; // NOT OK, just incrementing value *(myPtr++); // NOT OK, incrementing address *myPtr++; // NOT OK, incrementing address

26  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 25 1) // Fig. 5.14: fig05_14.cpp 2) // Attempting to modify a constant pointer to 3) // constant data. 4) #include 5) 6) using std::cout; 7) using std::endl; 8) 9) int main() 10) { 11) int x = 5, y; 12) 13) const int * const ptr = &x; // ptr is a constant pointer to a 14) // constant integer. ptr always 15) // points to the same location 16) // and the integer at that 17) // location cannot be modified. 18) cout << *ptr << endl; 19) *ptr = 7; 20) ptr = &y; 21) 22) return 0; 23) }

27  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 26 1) // Fig. 5.15: fig05_15.cpp 13) void bubbleSort( int *, const int ); 17)const int arraySize = 10; 18)int a[arraySize] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 26)bubbleSort( a, arraySize ); 36)void bubbleSort(int *array, const int size ) 37) { 38) void swap(int * const, int * const); 39) 40) for (int pass = 0; pass array[j+1]) 45) swap( &array[j], &array[j+1]); 46) } 47) 48) void swap(int * const element1Ptr, int * const element2Ptr) 49) { 50) int hold = *element1Ptr; 51) *element1Ptr = *element2Ptr; 52) *element2Ptr = hold; 53) }

28  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 27 sizeof operator sizeof –Returns size of operand in bytes –For arrays, sizeof returns number of bytes in the array ( the SIZE of 1 element ) * ( number of elements ) –if sizeof( int ) = 4, then int myArray[10]; cout << sizeof(myArray); // will print 40 sizeof can be used with –Variable names –Data Types –Constant values

29  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 28 sizeof operator size_t typedef unsigned int size_t defined in stdio.h header file It’s a pre-defined data type Example: size_t sz; sz = sizeof(int); // returns 4 double *dblPtr, dbl = 10.0; char *chrPtr, chr = 'a'; cout << "Size of Double Pointer = " << (sizeof dblPtr) << endl; cout << "Size of Char Pointer = " << (sizeof chrPtr) << endl; //Both pointer sizes are 4 bytes

30  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 29 sizeof operator 12) // Example Fig 5.17 13) char c; 14) short s; 15) int i; 16) long l; 17) float f; 18) double d; 19) long double ld; 20) int array[ 20 ], *ptr = array; 21) 22) cout << "sizeof c = " << sizeof c 23) << "\tsizeof(char) = " << sizeof (char) 24) << "\nsizeof s = " << sizeof s 25) << "\tsizeof(short) = " << sizeof (short) 26) << "\nsizeof i = " << sizeof i 27) << "\tsizeof(int) = " << sizeof (int) 28) << "\nsizeof l = " << sizeof l 29) << "\tsizeof(long) = " << sizeof (long) 30) << "\nsizeof f = " << sizeof f 31) << "\tsizeof(float) = " << sizeof (float) 32) << "\nsizeof d = " << sizeof d 33) << "\tsizeof(double) = " << sizeof (double) 34) << "\nsizeof ld = " << sizeof ld 35) << "\tsizeof(long double) = " << sizeof (long double) 36) << "\nsizeof array = " << sizeof array 37) << "\nsizeof ptr = " << sizeof ptr 38) << endl;

31  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 30 5.6Bubble Sort Using Call-by-reference Implement bubblesort using pointers –swap function must receive the address (using & ) of the array elements array elements have call-by-value default –Using pointers and the * operator, swap is able to switch the values of the actual array elements Psuedocode Initialize array print data in original order Call function bubblesort print sorted array Define bubblesort

32  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 31 1)//Fig. 5.15: fig05_15.cpp 2)//This program puts values into an array, sorts the values 3)//into ascending order, and prints the resulting array. 4) #include 9) #include 11) using namespace std; 12) 13) void bubbleSort( int *, const int ); 14) 15) int main() 16) { 17) const int arraySize = 10; 18) int a[arraySize] = {2,6,4,8,10,12,89,68,45,37 }; 19) int i; 20) 21) cout << "Data items in original order\n"; 22) 23) for ( i = 0; i < arraySize; i++ ) 24) cout << setw( 4 ) << a[ i ]; 25) 26) bubbleSort( a, arraySize ); // sort the array 27) cout << "\nData items in ascending order\n"; 28) 29) for ( i = 0; i < arraySize; i++ ) 30) cout << setw( 4 ) << a[ i ]; 31) 32) cout << endl; 33) return 0; 34) }

33  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 32 swap takes pointers (addresses of array elements) and dereferences them to modify the original array elements. 36)void bubbleSort( int *array, const int size ) 37){ 38) void swap( int * const, int * const ); 39) 40) for (int pass = 0; pass array[ j + 1 ] ) 45) swap( &array[ j ], &array[ j + 1 ] ); 46)} 47) 48)void swap(int *const element1Ptr, int *const element2Ptr ) 49){ 50) int hold = *element1Ptr; 51) *element1Ptr = *element2Ptr; 52) *element2Ptr = hold; 53)} Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89

34  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 33 5.7Pointer 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 is meaningless unless performed on an array 5 element int array on a machine using 4 byte int s –vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000 –vPtr += 2 ; sets vPtr to 3008 now vPtr points to v[ 2 ] pointer variable vPtr v[0] v[1]v[2] v[4] v[3] 30003004 3008 30123016 location

35  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 34 5.7Pointer Expressions and Pointer Arithmetic Subtracting pointers –Returns the number of elements between two addresses vPtr2 = &v[ 2 ]; vPtr = &v[ 0 ]; vPtr2 - vPtr == 2 // comparison Pointer comparison –Test which pointer points to the higher numbered array element –Must compare pointers of same type

36  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 35 5.7Pointer Expressions and Pointer Arithmetic Pointers assignment –If not the same type, a cast operator must be used –Exception: pointer to void (type void * ) –Void Pointer Generic pointer, represents any type of pointer No casting needed to convert a pointer to void pointer All pointers can be assigned to void pointer Void pointer cannot be assigned directly to another pointer. It must first be casted to the proper pointer type void pointers cannot be dereferenced

37  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 36 5.8The Relationship Between Pointers and Arrays Arrays and pointers closely related –Array name is like a constant pointer –Pointers can do array subscripting operations –Having declared an array b[ 5 ] and a pointer bPtr bPtr is equal to b bptr == b bptr is equal to the address of the first element of b bptr == &b[ 0 ]

38  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 37 5.8The Relationship Between Pointers and Arrays Accessing array elements with pointers –Element b[ n ] can be accessed by *( bPtr + n ) Called pointer/offset notation –Array itself can use pointer arithmetic. b[ 3 ] same as *(b + 3) –Pointers can be subscripted (pointer/subscript notation) bPtr[ 3 ] same as b[ 3 ]

39  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 38 5.9Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; char suit[4][9] = {"Hearts", "Diamonds", "Clubs", "Spades" }; char *suit1 = {"Hearts"}; char suite1[] = {"Hearts"}; char *suit2 = {"Diamonds"}; char *suit3 = {"Clubs"}; char *suit4 = {"Spades"}; char suite5 [][5] = {"1234", "aaa", "bbb"}; char suite6 [3][5] = {"1234", "aaa", "bbb"}; 1 st [ ], number of strings 2 nd [ ], # of elements in each string, must be > largest string

40  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 39 5.9Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; –Each element of suit is a pointer to a char * (a string) –The strings are not in the array, only pointers to the strings are in the array –suit array has a fixed size, but strings can be of any size suit[3]suit[2]suit[1]suit[0] ’H’’e’’a’’r’’t’’s’ ’\0’ ’D’ ’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

41  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 40 5.10Case Study: A Card Shuffling and Dealing Simulation Card shuffling program –Use an array of pointers to strings, to store suit names –Use a double scripted array (suit by value) –Place 1-52 into the array to specify the order in which the cards are dealt deck[2][12] represents the King of Clubs Hearts Diamonds Clubs Spades 0 1 2 3 Ace TwoThreeFourFiveSixSevenEightNineTenJackQueenKing 0123456789101112 Clubs King One

42  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 41 5.10Case Study: A Card Shuffling and Dealing Simulation Pseudocode for shuffling and dealing simulation For each of the 52 cards Place card number in randomly selected unoccupied slot of deck For each of the 52 cards Find card number in deck array and print face and suit of card Choose slot of deck randomly While chosen slot of deck has been previously chosen Choose slot of deck randomly Place card number in chosen slot of deck For each slot of the deck array If slot contains card number Print the face and suit of the card Second refinement Third refinement First refinement Initialize the suit array Initialize the face array Initialize the deck array Shuffle the deck Deal 52 cards

43  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 42 1. Initialize suit and face arrays 1.1 Initialize deck array 2. Call function shuffle 2.1 Call function deal 1// Fig. 5.24: fig05_24.cpp 2// Card shuffling dealing program 3#include 4 5using std::cout; 6using std::ios; 7 8#include 9 10using std::setw; 11using std::setiosflags; 12 13#include 14#include 15 16void shuffle( int [][ 13 ] ); 17void deal( const int [][ 13 ], const char *[], const char *[] ); 18 19int main() 20{ 21 const char *suit[ 4 ] = 22 { "Hearts", "Diamonds", "Clubs", "Spades" }; 23 const char *face[ 13 ] = 24 { "Ace", "Deuce", "Three", "Four", 25 "Five", "Six", "Seven", "Eight", 26 "Nine", "Ten", "Jack", "Queen", "King" }; 27 int deck[ 4 ][ 13 ] = { 0 }; 28 29 srand( time( 0 ) ); 30 31 shuffle( deck ); 32 deal( deck, face, suit ); 33

44  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 43 3. Define functions 34 return 0; 35} 36 37void shuffle( int wDeck[][ 13 ] ) 38{ 39 int row, column; 40 41 for ( int card = 1; card <= 52; card++ ) { 42 do { 43 row = rand() % 4; 44 column = rand() % 13; 45 } while( wDeck[ row ][ column ] != 0 ); 46 47 wDeck[ row ][ column ] = card; 48 } 49} 50 51void deal( const int wDeck[][ 13 ], const char *wFace[], 52 const char *wSuit[] ) 53{ 54 for ( int card = 1; card <= 52; card++ ) 55 56 for ( int row = 0; row <= 3; row++ ) 57 58 for ( int column = 0; column <= 12; column++ ) 59 60 if ( wDeck[ row ][ column ] == card ) 61 cout << setw( 5 ) << setiosflags( ios::right ) 62 << wFace[ column ] << " of " 63 << setw( 8 ) << setiosflags( ios::left ) 64 << wSuit[ row ] 65 << ( card % 2 == 0 ? '\n' : '\t' ); 66} The numbers 1-52 are randomly placed into the deck array. Searches deck for the card number, then prints the face and suit.

45  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 44 Program Output Six of Clubs Seven of Diamonds Ace of Spades Ace of Diamonds Ace of Hearts Queen of Diamonds Queen of Clubs Seven of Hearts Ten of Hearts Deuce of Clubs Ten of Spades Three of Spades Ten of Diamonds Four of Spades Four of Diamonds Ten of Clubs Six of Diamonds Six of Spades Eight of Hearts Three of Diamonds Nine of Hearts Three of Hearts Deuce of Spades Six of Hearts Five of Clubs Eight of Clubs Deuce of Diamonds Eight of Spades Five of Spades King of Clubs King of Diamonds Jack of Spades Deuce of Hearts Queen of Hearts Ace of Clubs King of Spades Three of Clubs King of Hearts Nine of Clubs Nine of Spades Four of Hearts Queen of Spades Eight of Diamonds Nine of Diamonds Jack of Diamonds Seven of Clubs Five of Hearts Five of Diamonds Four of Clubs Jack of Hearts Jack of Clubs Seven of Spades

46  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 45 5.11Function Pointers Pointers to functions –Contain the address of the function –Similar to how an array name is the address of its first element –Function name is starting address of code that defines function Function pointers can be –Passed to functions –Stored in arrays –Assigned to other function pointers

47  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 46 5.11Function Pointers Example: bubblesort –Function bubble takes a function pointer The function determines whether the the array is sorted into ascending or descending sorting –The argument in bubble for the function pointer bool ( *compare )( int, int ) tells bubble to expect a pointer to a function that takes two int s and returns a bool –If the parentheses were left out bool *compare( int, int ) would declare a function that receives two integers and returns a pointer to a bool

48  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 47 1. Initialize array 2. Prompt for ascending or descending sorting 2.1 Put appropriate function pointer into bubblesort 2.2 Call bubble 3. Print results 1// Fig. 5.26: fig05_26.cpp 2// Multipurpose sorting program using function pointers 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8 9#include 10 11using std::setw; 12 13void bubble( int [], const int, bool (*)( int, int ) ); 14bool ascending( int, int ); 15bool descending( int, int ); 16 17int main() 18{ 19 const int arraySize = 10; 20 int order, 21 counter, 22 a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 23 24 cout << "Enter 1 to sort in ascending order,\n" 25 << "Enter 2 to sort in descending order: "; 26 cin >> order; 27 cout << "\nData items in original order\n"; 28 29 for ( counter = 0; counter < arraySize; counter++ ) 30 cout << setw( 4 ) << a[ counter ]; 31 32 if ( order == 1 ) { 33 bubble( a, arraySize, ascending ); 34 cout << "\nData items in ascending order\n"; Notice the function pointer parameter.

49  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 48 3.1 Define functions 35 } 36 else { 37 bubble( a, arraySize, descending ); 38 cout << "\nData items in descending order\n"; 39 } 40 41 for ( counter = 0; counter < arraySize; counter++ ) 42 cout << setw( 4 ) << a[ counter ]; 43 44 cout << endl; 45 return 0; 46} 47 48void bubble( int work[], const int size, 49 bool (*compare)( int, int ) ) 50{ 51 void swap( int * const, int * const ); // prototype 52 53 for ( int pass = 1; pass < size; pass++ ) 54 55 for ( int count = 0; count < size - 1; count++ ) 56 57 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) 58 swap( &work[ count ], &work[ count + 1 ] ); 59} 60 61void swap( int * const element1Ptr, int * const element2Ptr ) 62{ 63 int temp; 64 65 temp = *element1Ptr; 66 *element1Ptr = *element2Ptr; 67 *element2Ptr = temp; 68} ascending and descending return true or false. bubble calls swap if the function call returns true. Notice how function pointers are called using the dereferencing operator. The * is not required, but emphasizes that compare is a function pointer and not a function.

50  2000 Deitel & Associates, Inc.  New Hampshire Technical Institute All rights reserved. Outline Click to edit Master subtitle style CP 107 Spring 2002 M. Saleem Yusuf 49 3.1 Define functions Program output 69 70bool ascending( int a, int b ) 71{ 72 return b < a; // swap if b is less than a 73} 74 75bool descending( int a, int b ) 76{ 77 return b > a; // swap if b is greater than a 78} 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 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 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 45 37 Data items in descending order 89 68 45 37 12 10 8 6 4 2

51  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 50 Pointer to Function void vline(int i); funciton prototype void hline(int i); funciton prototype p is Pointer to a function that take an int and returns nothing. void (*p)(int); p = vline; // Pass the address of function vline (*p)(4); // call or execute function vline; p = hline; // Pass the address of function hline (*p)(10); // call or execute function hline;

52  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 51 Array of Pointers to Function void vline(int i); funciton prototype void hline(int i); funciton prototype pArray is an array of 2 pointers to a function that take an int and returns nothing. void (*pArray[2])(int); pArray[0] = vline; // Pass address of function pArray[1] = hline; // Pass address of function (*pArray[0])(8); // call or execute function vline; pArray[1](20); // call or execute function hline; // declare the array & initialize it void (*pArray1[2])(int) = {vline, hline};

53  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 52 5.12.1 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes –'z' is the integer value of z, which is 122 String –Series of characters treated as one unit –Can include letters, digits, special characters +, -, *... –String literal (string constants) –Array of characters, ends with null character '\0' –Strings are constant pointers (like arrays) Enclosed in double quotes, for example: "I like C++" Value of string is the address of its first character

54  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 53 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 a pointer to string “blue”, colorPtr, and stores it somewhere in memory

55  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 54 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' ) cin.getline –Reads a line of text –Using cin.getline cin.getline( array, size, delimiter character);

56  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 55 5.12.1 Fundamentals of Characters and Strings cin.getline –Copies input into specified array until either One less than the size is reached The delimiter character is input –Example char sentence[ 80 ]; cin.getline( sentence, 80, '\n' );

57  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 56 5.12.2 String Manipulation Functions of the String-handling Library String handling library provides functions to –Manipulate strings –Compare strings –Search strings –Tokenize strings (separate them into logical pieces) ASCII character code –Strings are compared using their character codes –Easy to make comparisons (greater than, less than, equal to) Tokenizing –Breaking strings into tokens, separated by user-specified characters –Tokens are usually logical units, such as words (separated by spaces) –"This is my string" has 4 word tokens (separated by spaces)

58  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 57 5.12.2String Manipulation Functions of the String-handling Library char *strcpy( char *s1, const char *s2 ); Copies the string s2 into the character array s1. The value of s1 is returned. char *strncpy( char *s1, const char *s2, size_t n ); Copies at most n characters of the string s2 into the character array s1. The value of s1 is returned. char *strcat( char *s1, const char *s2 ); Appends the string s2 to the string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. char *strncat( char *s1, const char *s2, size_t n ); Appends at most n characters of string s2 to string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. int strcmp( const char *s1, const char *s2 ); Compares the string s1 with the string s2. The function returns a value of zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.

59  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 58 5.12.2String Manipulation Functions of the String-handling Library (III) int strncmp( const char *s1, const char *s2, size_t n ); Compares up to n characters of the string s1 with the string s2. The function returns zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively. char *strtok( char *s1, const char *s2 ); A sequence of calls to strtok breaks string s1 into “tokens”—logical pieces such as words in a line of text—delimited by characters contained in string s2. The first call contains s1 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.

60  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 59 Examples – strcpy, strncpy 1)// Fig. 5.30: fig05_30.cpp 2)// Using strcpy and strncpy 3)#include 4) 5)using std::cout; 6)using std::endl; 7) 8)#include 9) 10)int main() 11){ 12) char x[] = "Happy Birthday to You"; 13) char y[ 25 ], z[ 15 ]; 14) 15) cout << "The string in array x is: " << x 16) << "\nThe string in array y is: " << strcpy( y, x ) 17) << '\n'; 18) strncpy( z, x, 14 ); // does not copy null character 19) z[ 14 ] = '\0'; z[14] is 15 th character!!! 20) cout << "The string in array z is: " << z << endl; 21) 22) return 0; 23)}

61  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 60 Examples – strcat, strncat 1) // Fig. 5.31: fig05_31.cpp 2) // Using strcat and strncat 3) #include 4) 5) using std::cout; 6) using std::endl; 7) 8) #include 9) 10) int main() 11) { 12) char s1[ 20 ] = "Happy "; 13) char s2[] = "New Year "; 14) char s3[ 40 ] = ""; 15) 16) cout << "s1 = " << s1 << "\ns2 = " << s2; 17) cout << "\nstrcat(s1, s2) = " << strcat( s1, s2 ); 18) cout << "\nstrncat(s3, s1, 6) = " << strncat( s3, s1, 6 ); 19) cout << "\nstrcat(s3, s1) = " << strcat( s3, s1 ) << endl; 20) 21) return 0; 22) }

62  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 61 Examples – strcmp, strncmp 1)// Fig. 5.32: fig05_32.cpp 2)// Using strcmp and strncmp 3)#include 8)#include 12)#include 13)using namespace std; 14)int main() { 16) char *s1 = "Happy New Year"; 17) char *s2 = "Happy New Year"; 18) char *s3 = "Happy Holidays"; 19) 20) cout << "s1 = " << s1 << "\ns2 = " << s2 21) << "\ns3 = " << s3 << "\n\nstrcmp(s1, s2) = " 22) << setw( 2 ) << strcmp( s1, s2 ) 23) << "\nstrcmp(s1, s3) = " << setw( 2 ) 24) << strcmp( s1, s3 ) << "\nstrcmp(s3, s1) = " 25) << setw( 2 ) << strcmp( s3, s1 ); 26) 27) cout << "\n\nstrncmp(s1, s3, 6) = " << setw( 2 ) 28) << strncmp( s1, s3, 6 ) << "\nstrncmp(s1, s3, 7) = " 29) << setw( 2 ) << strncmp( s1, s3, 7 ) 30) << "\nstrncmp(s3, s1, 7) = " 31) << setw( 2 ) << strncmp( s3, s1, 7 ) << endl; 32) return 0; 33)}

63  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 62 Examples – strlen 1) // Fig. 5.34: fig05_34.cpp 2) // Using strlen 3) #include 4) 5) using std::cout; 6) using std::endl; 7) 8) #include 9) 10) int main() 11) { 12) char *string1 = "abcdefghijklmnopqrstuvwxyz"; 13) char *string2 = "four"; 14) char *string3 = "Boston"; 15) 16) cout << "The length of \"" << string1 17) << "\" is " << strlen( string1 ) 18) << "\nThe length of \"" << string2 19) << "\" is " << strlen( string2 ) 20) << "\nThe length of \"" << string3 21) << "\" is " << strlen( string3 ) << endl; 22) 23) return 0; 24) }

64  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 63 Examples – strtok 1) // Fig. 5.33: fig05_33.cpp 2) // Using strtok 3) #include 5) using std::cout; 6) using std::endl; 8) #include 9) 10) int main() 11) { 12) char string[] = "This is a sentence with 7 tokens"; 13) char *tokenPtr; 14) 15) cout << "The string to be tokenized is:\n" << string 16) << "\n\nThe tokens are:\n"; 17) 18) tokenPtr = strtok( string, " " ); 19) 20) while ( tokenPtr != NULL ) { 21) cout << tokenPtr << '\n'; 22) tokenPtr = strtok( NULL, " " ); 23) } 24) 25) return 0; 26) }

65  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 64 LAB #include #include "msoft.h" // used by function clrscrn() using namespace std; char TAB = '\t'; char NEWLINE = '\n'; const int FIRST_MENU_ENTRY = 0; const int LAST_MENU_ENTRY = 3; const int MAX_MENU_ITEMS = 4; const char *MenuItem0_String = "0 Demo of string func strcmp"; const char *MenuItem1_String = "1 Demo of string func strncmp"; const char *MenuItem2_String = "2 Demo of string func strcat"; const char *MenuItem3_String = "3 Demo of string func strncap"; const int MAX_SIZE = 80; void printMenu( void ); void MenuItem0( char * );

66  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 65 LAB int main() { char *reference_string = "This is the reference string"; void (*MenuItem_Array[MAX_MENU_ITEMS])(char *) = { MenuItem0, // Demo use of string function strcmp MenuItem1, MenuItem2, MenuItem3 }; int choice = 0; while ( choice != 4 ) { do { printMenu(); cin >> choice; } while ( choice 4 ); if (choice >= FIRST_MENU_ENTRY && choice <= LAST_MENU_ENTRY) (*MenuItem_Array[ choice ])( reference_string ); else cout << "Program Ended.\n"; } //while return 0; }

67  2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 66 LAB void printMenu( void ) { cout << NEWLINE << TAB << "Enter a choice:" << NEWLINE << TAB << MenuItem0_String << NEWLINE << TAB << MenuItem1_String << NEWLINE << TAB << MenuItem2_String << NEWLINE << TAB << MenuItem3_String << NEWLINE << "\t4 End program\n\n : "; }


Download ppt " 2000 Deitel & Associates, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 1 5.1Introduction Pointers –Powerful, but difficult to master."

Similar presentations


Ads by Google