pointers and pointer-based strings - exercises ... 504 chapter 8 pointers and pointer-based strings...

Download Pointers and Pointer-Based Strings - Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for statement to print the elements of array numbers using pointer/offset

If you can't read please download the document

Post on 16-May-2018

221 views

Category:

Documents

1 download

Embed Size (px)

TRANSCRIPT

  • 8Pointers and Pointer-Based Strings

    O B J E C T I V E SIn this chapter you will learn:

    What pointers are.

    The similarities and differences between pointers and references and when to use each.

    To use pointers to pass arguments to functions by reference.

    The close relationships among pointers, arrays and strings.

    To use pointers to functions.

    To declare and use arrays of strings.

    Addresses are given to us to conceal our whereabouts.Saki (H. H. Munro)

    By indirection find direction out.William Shakespeare

    Many things, having full referenceTo one consent, may work contrariously.William Shakespeare

    You will find it a very good practice always to verify your references, sir!Dr. Routh

    You cant trust code that you did not totally create yourself. (Especially code from companies that employ people like me.)Ken Thompson

    cpphtp5_08_IM.fm Page 502 Thursday, December 23, 2004 4:14 PM

  • Self-Review Exercises 503

    Self-Review Exercises8.1 Answer each of the following:

    a) A pointer is a variable that contains as its value the of another variable.ANS: address.b) The three values that can be used to initialize a pointer are ,

    and .ANS: 0, NULL, an address. c) The only integer that can be assigned directly to a pointer is .ANS: 0.

    8.2 State whether the following are true or false. If the answer is false, explain why.a) The address operator & can be applied only to constants and to expressions.ANS: False. The operand of the address operator must be an lvalue; the address operator

    cannot be applied to constants or to expressions that do not result in references.b) A pointer that is declared to be of type void * can be dereferenced.ANS: False. A pointer to void cannot be dereferenced. Such a pointer does not have a type

    that enables the compiler to determine the number of bytes of memory to dereferenceand the type of the data to which the pointer points.

    c) Pointers of different types can never be assigned to one another without a cast opera-tion.

    ANS: False. Pointers of any type can be assigned to void pointers. Pointers of type void canbe assigned to pointers of other types only with an explicit type cast.

    8.3 For each of the following, write C++ statements that perform the specified task. Assumethat double-precision, floating-point numbers are stored in eight bytes and that the starting addressof the array is at location 1002500 in memory. Each part of the exercise should use the results ofprevious parts where appropriate.

    a) Declare an array of type double called numbers with 10 elements, and initialize the ele-ments to the values 0.0, 1.1, 2.2, , 9.9. Assume that the symbolic constant SIZE hasbeen defined as 10.

    ANS: double numbers[ SIZE ] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8,9.9 };

    b) Declare a pointer nPtr that points to a variable of type double.ANS: double *nPtr;c) Use a for statement to print the elements of array numbers using array subscript nota-

    tion. Print each number with one position of precision to the right of the decimal point.ANS: cout

  • 504 Chapter 8 Pointers and Pointer-Based Strings

    f) Use a for statement to print the elements of array numbers using pointer/offset notationwith the array name as the pointer.

    ANS: cout

  • Self-Review Exercises 505

    k) Determine the length of the string in s1, and print the result.ANS: cout

  • 506 Chapter 8 Pointers and Pointer-Based Strings

    f) ++z; ANS: Error: Trying to modify an array name with pointer arithmetic.

    Correction: Use a pointer variable instead of the array name to accomplish pointerarithmetic, or subscript the array name to refer to a specific element.

    g) char s[ 10 ]; cout

  • Exercises 507

    a) Declare an array of type unsigned int called values with five elements, and initializethe elements to the even integers from 2 to 10. Assume that the symbolic constant SIZEhas been defined as 5.

    ANS: unsigned values[ SIZE ] = { 2, 4, 6, 8, 10 }; b) Declare a pointer vPtr that points to an object of type unsigned int.ANS: unsigned *vPtr; c) Use a for statement to print the elements of array values using array subscript notation. ANS:

    for ( int i = 0; i < SIZE; i++ ) cout

  • 508 Chapter 8 Pointers and Pointer-Based Strings

    8.11 Perform the task specified by each of the following statements:a) Write the function header for function zero that takes a long integer array parameter

    bigIntegers and does not return a value.ANS: void zero( long bigIntegers[] ) or

    void zero( long *bigIntegers )b) Write the function prototype for the function in part (a).ANS: void zero( long [] ); or

    void zero( long * );c) Write the function header for function add1AndSum that takes an integer array parameter

    oneTooSmall and returns an integer.ANS: int add1Andsum( int oneTooSmall[] ) or

    int add1Andsum( int *oneTooSmall )d) Write the function prototype for the function described in part (c).ANS: int add1Andsum( int [] ); or int add1Andsum( int * );

    Note: Exercise 8.12 through Exercise 8.15 are reasonably challenging. Once you have solved these problems, you ought to be able to implement many popular card games.8.12 Modify the program in Fig. 8.27 so that the card dealing function deals a five-card pokerhand. Then write functions to accomplish each of the following:

    a) Determine whether the hand contains a pair.b) Determine whether the hand contains two pairs.c) Determine whether the hand contains three of a kind (e.g., three jacks).d) Determine whether the hand contains four of a kind (e.g., four aces).e) Determine whether the hand contains a flush (i.e., all five cards of the same suit).f) Determine whether the contains a straight (i.e., five cards of consecutive face values).ANS:

    1 // Exercise 8.12 Solution: DeckOfCards.h2 // Definition of class DeckOfCards that 3 // represents a deck of playing cards.45 // DeckOfCards class definition6 class DeckOfCards7 {8 public:9 DeckOfCards(); // constructor initializes deck

    10 void shuffle(); // shuffle the deck11 void deal(); // deal a five card poker hand12 void pair(); // pair determines if the hand contains one or two pair13 void threeOfKind(); // check if three of a kind14 void fourOfKind(); // check if four of a kind15 void flushHand(); // check for a flush16 void straightHand(); // check for a straight hand17 private:18 int deck[ 4 ][ 13 ]; // represents deck of cards19 const char *suit[ 4 ]; // card suit20 const char *face[ 13 ]; // card face21 int hand[ 5 ][ 2 ]; // represents five-card poker hand22 }; // end class DeckOfCards

    cpphtp5_08_IM.fm Page 508 Thursday, December 23, 2004 4:14 PM

  • Exercises 509

    1 // Exercise 8.12: DeckOfCards.cpp2 // Member-function definitions for class DeckOfCards that simulates3 // the shuffling and dealing of a deck of playing cards.4 #include 5 using std::cout;6 using std::left;7 using std::right;89 #include

    10 using std::setw;1112 #include // prototypes for rand and srand13 using std::rand;14 using std::srand;1516 #include // prototype for time17 using std::time;1819 #include "DeckOfCards.h" // DeckOfCards class definition2021 // DeckOfCards default constructor initializes deck22 DeckOfCards::DeckOfCards()23 {24 char *suitValue[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };25 char *faceValue[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", 26 "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };2728 // initialize suit29 for ( int i = 0; i < 4; i++ )30 suit[ i ] = suitValue[ i ];3132 // initialize face33 for ( int i = 0; i < 13; i++ )34 face[ i ] = faceValue[ i ];3536 // loop through rows of deck37 for ( int row = 0; row

  • 510 Chapter 8 Pointers and Pointer-Based Strings

    56 for ( int card = 1; card

  • Exercises 511

    111 cout

  • 512 Chapter 8 Pointers and Pointer-Based Strings

    166 // bubble sort column locations167 for ( int pass = 1; pass < 5; pass++ )168169 for ( int comp = 0; comp < 4; comp++ )170171 if ( s[ comp ] > s[ comp + 1 ] ) 172 {173 temp = s[ comp ];174 s[ comp ] = s[ comp + 1 ];175 s[ comp + 1 ] = temp;176 } // end if177178 // check if sorted columns are a straight179 if ( s[ 4 ] - 1 == s[ 3 ] && s[ 3 ] - 1 == s[ 2 ] 180 && s[ 2 ] - 1 == s[ 1 ] && s[ 1 ] - 1 == s[ 0 ] ) 181 {182 cout

  • Exercises 513

    8.13 Use the functions developed in Exercise 8.12 to write a program that deals two five-cardpoker hands, evaluates each hand and determines which is the better hand.

    8.14 Modify the program developed in Exercise 8.13 so that it can simulate the dealer. The deal-ers five-card hand is dealt face down so the player cannot see it. The program should then evaluatethe dealers hand, and, based on the quality of the hand, the dealer should draw one, two or threemore cards to replace the corresponding number of unneeded cards in the original hand. The pro-gram should then reevaluate the dealers hand. [Caution: This is a difficult problem!]

    8.15 Modify the program developed in Exercise 8.14 so that it handles the dealers hand, but theplayer is allowed to decide which cards of the players hand to replace. The program should thenevaluate both hands and determine who wins. Now use this new program to play 20 games againstthe computer. Who wins more games, you or the computer? Have one of your friends play 20 gamesagainst the computer. Who wins more games? Based on the results of these games, make appropriatemodifications to refine your poker-playing pro

Recommended

View more >