Вы находитесь на странице: 1из 14

256 Chapter 7 C Pointers: Solutions

Exercises
7.7 Answer each of the following:
a) The operator returns the location in memory where its operand is stored.
ANS: address (&).
b) The operator returns the value of the object to which its operand points.
ANS: indirection (*).
c) To simulate call-by-reference when passing a nonarray variable to a function, it is nec-
essary to pass the of the variable to the function.
ANS: address.
7.8 State whether the following are trueor false. If false, explain why.
a) Two pointers that point to different arrays cannot be compared meaningfully.
ANS: True. It is not possible to know where these arrays will be stored in advance.
b) Because the name of an array is a pointer to the first element of the array, array names
may be manipulated in precisely the same manner as pointers.
ANS: False. Array names cannot be modified to point to another location in memory.
7.9 Answer each of the following. Assume that unsigned integers are stored in 2 bytes and that
the starting address of the array is at location 1002500 in memory.

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 257

a) Define an array of type unsigned int called values with five elements, and initialize the
elements to the even integers from 2 to 10. Assume the symbolic constant SIZE has been
defined as 5.
ANS: unsigned int values[ SIZE ] = { 2, 4, 6, 8, 10 };
b) Define a pointer vPtr that points to an object of type unsigned int.
ANS: unsigned int *vPtr;
c) Print the elements of array values using array subscript notation. Use a for statement
and assume integer control variable i has been defined.
ANS:
for ( i = 0; i < SIZE; i++ )
printf( “%d ”, values[ i ] );
d) Give two separate statements that assign the starting address of array values to pointer
variable vPtr.
ANS:
1) vPtr = values;
2) vPtr = &values[ 0 ];
e) Print the elements of array values using pointer/offset notation.
ANS:
for ( i = 0; i < SIZE; i++ )
printf( “%d”, *( vPtr + i ) );
f) Print the elements of array values using pointer/offset notation with the array name as
the pointer.
ANS:
for ( i = 0; i < SIZE; i++ )
printf( “%d”, *( values + i ) );
g) Print the elements of array values by subscripting the pointer to the array.
ANS:
for ( i = 0; i < SIZE; i++ )
printf( “%d”, vPtr[ i ] );
h) Refer to element 5 of array values using array subscript notation, pointer/offset nota-
tion with the array name as the pointer, pointer subscript notation, and pointer/offset
notation.
ANS: values[ 4 ], *( values + 4 ), vPtr[ 4 ], *( vPtr + 4 ).
i) What address is referenced by vPtr + 3?What value is stored at that location?
ANS: 1002506; 8.
j) Assuming vPtr points to values[ 4 ], what address is referenced by vPtr -= 4. What
value is stored at that location?
ANS: 1002500; 2.
7.10 For each of the following, write a single statement that performs the indicated task. Assume
that long integer variables value1 and value2 have been defined and that value1 hasbeen initialized
to 200000.
a) Define the variable lPtr to be a pointer to an object of type long.
ANS: long *lPtr;
b) Assign the address of variable value1 to pointer variable lPtr.
ANS: lPtr = &value1;
c) Print the value of the object pointed to by lPtr.
ANS: printf( “%ld\n”, *lPtr );
d) Assign the value of the object pointed to by lPtr to variable value2.
ANS: value2 = *lPtr;
e) Print the value of value2.
ANS: printf( “%ld\n”, value2 );
f) Print the address of value1.
ANS: printf( “%p\n”, &value1 );

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
258 Chapter 7 C Pointers: Solutions

g) Print the address stored in lPtr. Is the value printed the same as the address of value1?
ANS: printf( “%p\n”, lPtr); /* The value is the same */

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
262 Chapter 7 C Pointers: Solutions

7.16 (Card Shuffling and Dealing Modification) In the card shuffling and dealing program of
Fig. 7.24, we intentionally used an inefficient shuffling algorithm that introduced the possibility of

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 263

indefinite postponement. In this problem, you’ll create a high-performance shuffling algorithm that
avoids indefinite postponement.
Modify the program of Fig. 7.24 as follows. Begin by initializing the deck array as shown in
Fig. 7.29. Modify the shuffle function to loop row-by-row and column-by-column through the
array, touching every element once. Each element should be swapped with a randomly selected ele-
ment of the array.

Unshuffled deck array

0 1 2 3 4 5 6 7 8 9 10 11 12
0 1 2 3 4 5 6 7 8 9 10 11 12 13
1 14 15 16 17 18 19 20 21 22 23 24 25 26
2 27 28 29 30 31 32 33 34 35 36 37 38 39
3 40 41 42 43 44 45 46 47 48 49 50 51 52

Fig. 7.29 | Unshuffled deck array.

Sample shuffled deck array

0 1 2 3 4 5 6 7 8 9 10 11 12
0 19 40 27 25 36 46 10 34 35 41 18 2 44

1 13 28 14 16 21 30 8 11 31 17 24 7 1

2 12 33 15 42 43 23 45 3 29 32 4 47 26

3 50 38 52 39 48 51 9 5 37 49 22 6 20

Fig. 7.30 | Sample shuffled deck array.

Print the resulting array to determine if the deck is satisfactorily shuffled (as in Fig. 7.30, for
example). You may want your program to call the shuffle function several times to ensure a satis-
factory shuffle.
Note that although the approach in this problem improves the shuffling algorithm, the deal-
ing algorithm still requires searching the deck array for card 1, then card 2, then card 3, and so on.
Worse yet, even after the dealing algorithm locates and deals the card, the algorithm continues
searching through the remainder of the deck. Modify the program of Fig. 7.24 so that once a card
is dealt, no further attempts are made to match that card number, and the program immediately
proceeds with dealing the next card. In Chapter 10, we develop a dealing algorithm that requires
only one operation per card.
ANS:

1 /* Exercise 7.16 Solution */


2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <time.h>
5

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
264 Chapter 7 C Pointers: Solutions

6 /* function prototypes */
7 void shuffle( int workDeck[][ 13 ] );
8 void deal( int workDeck[][ 13 ], char *workFace[], char *workSuit[] );
9
10 int main()
11 {
12 int card = 1; /* card counter */
13 int row; /* loop counter */
14 int column; /* loop counter */
15 int deck[ 4 ][ 13 ]; /* array of cards */
16
17 /* define arrays of card suits and faces */
18 char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"};
19 char *face[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
20 "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
21
22 srand( time( NULL ) );
23
24 /* initialize deck */
25 for ( row = 0; row <= 3; row++ ) {
26
27 for ( column = 0; column <= 12; column++ ) {
28 deck[ row ][ column ] = card++;
29 } /* end for */
30
31 } /* end for */
32
33 shuffle( deck );
34 deal( deck, face, suit );
35
36 return 0; /* indicate successful termination */
37 } /* end main */
38
39 /* introduce another way to shuffle */
40 void shuffle( int workDeck[][ 13 ] )
41 {
42 int temp; /* temporary holder */
43 int row; /* loop counter */
44 int column; /* loop counter */
45 int randRow; /* random suit */
46 int randColumn; /* random face */
47
48 /* run through the loop and touch every element once */
49 for ( row = 0; row <= 3; row++ ) {
50
51 for ( column = 0; column <= 12; column++ ) {
52
53 /* generate a random card */
54 randRow = rand() % 4;
55 randColumn = rand() % 13;
56
57 /* swap random card with current card */
58 temp = workDeck[ row ][ column ];
59 workDeck[ row ][ column ] = workDeck[ randRow ][ randColumn ];

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 265

60 workDeck[ randRow ][ randColumn ] = temp;


61 } /* end for */
62
63 } /* end for */
64
65 } /* end function shuffle */
66
67 /* deal the cards */
68 void deal( int workDeck2[][ 13 ], char *workFace[], char *workSuit[] )
69 {
70 int card; /* card counter */
71 int row; /* loop counter */
72 int column; /* loop counter */
73
74 /* loop through and print the cards */
75 for ( card = 1; card <= 52; card++ ) {
76
77 /* loop through rows */
78 for ( row = 0; row <= 3; row++ ) {
79
80 /* loop through columns */
81 for ( column = 0; column <= 12; column++ ) {
82
83 /* if current card equals card, then deal */
84 if ( workDeck2[ row ][ column ] == card ) {
85 printf("%5s of %-8s", workFace[ column ], workSuit[ row ]);
86 card % 2 == 0 ? putchar( '\n' ) : putchar( '\t' );
87 break; /* break loop */
88 } /* end if */
89
90 } /* end for */
91
92 } /* end for */
93
94 } /* end for */
95
96 } /* end function deal */

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
266 Chapter 7 C Pointers: Solutions

Eight of Spades Ace of Spades


Five of Hearts Ace of Hearts
Eight of Diamonds Queen of Spades
Deuce of Hearts Seven of Hearts
Seven of Clubs Six of Hearts
Four of Clubs Ace of Clubs
Six of Spades Ten of Diamonds
Ten of Hearts King of Hearts
Four of Diamonds Four of Hearts
Jack of Diamonds Three of Diamonds
Deuce of Spades Queen of Clubs
Three of Hearts Six of Clubs
Nine of Hearts Nine of Diamonds
King of Spades Seven of Diamonds
Five of Spades Seven of Spades
Four of Spades Ten of Spades
King of Diamonds Nine of Spades
Deuce of Clubs Jack of Hearts
Ace of Diamonds Ten of Clubs
Eight of Hearts Six of Diamonds
Nine of Clubs Five of Diamonds
Three of Clubs Deuce of Diamonds
Queen of Hearts King of Clubs
Queen of Diamonds Jack of Clubs
Five of Clubs Three of Spades
Jack of Spades Eight of Clubs

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
272 Chapter 7 C Pointers: Solutions

7.19 What does this program do?

1 /* ex07_19.c */
2 /* What does this program do? */
3 #include <stdio.h>
4
5 void mystery1( char *s1, const char *s2 ); /* prototype */
6
7 int main( void )
8 {
9 char string1[ 80 ]; /* create char array */
10 char string2[ 80 ]; /* create char array */

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 273

11
12 printf( "Enter two strings: " );
13 scanf( "%s%s" , string1, string2 );
14 mystery1( string1, string2 );
15 printf("%s", string1 );
16 return 0; /* indicates successful termination */
17 } /* end main */
18
19 /* What does this function do? */
20 void mystery1( char *s1, const char *s2 )
21 {
22 while ( *s1 != '\0' ) {
23 s1++;
24 } /* end while */
25
26 for ( ; *s1 = *s2; s1++, s2++ ) {
27 ; /* empty statement */
28 } /* end for */
29 } /* end function mystery1 */

ANS: Concatenates strings.

Enter two strings: string1 string2


string1string2

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 273

7.20 What does this program do?

1 /* ex07_20.c */
2 /* what does this program do? */
3 #include <stdio.h>
4
5 int mystery2( const char *s ); /* prototype */
6
7 int main( void )
8 {
9 char string[ 80 ]; /* create char array */
10
11 printf( "Enter a string: ");
12 scanf( "%s", string );
13 printf( "%d\n", mystery2( string ) );
14 return 0; /* indicates successful termination */
15 } /* end main */
16
17 /* What does this function do? */
18 int mystery2( const char *s )
19 {
20 int x; /* counter */
21
22 /* loop through string */
23 for ( x = 0; *s != '\0'; s++ ) {
24 x++;
25 } /* end for */
26
27 return x;
28 } /* end function mystery2 */

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
274 Chapter 7 C Pointers: Solutions

ANS: Determines the length of a string.

Enter a string: string1


7

7.21 Find the error in each of the following program segments. If the error can be corrected, ex-
plain how.
a) int *number;
printf( "%d\n", *number );
ANS: number has not been assigned to point to a location in memory.
b) float *realPtr;
long *integerPtr;
integerPtr = realPtr;
ANS: A pointer cannot be assigned to a different type, other than void *.
c) int * x, y;
x = y;
ANS: There are two possible solutions. 1) The indirection operator (*) is not distributive
and would be required for y, which would result in a valid pointer assignment. 2) y
as it is defined is a valid integer variable, and would require the address operator (&)
in the pointer assignment statement.
d) char s[] = "this is a character array";
int count;
for ( ; *s != '\0'; s++)
printf( "%c ", *s );
ANS: s should be defined as char *; a constant pointer cannot be moved.
e) short *numPtr, result;
void *genericPtr = numPtr;
result = *genericPtr + 7;
ANS: A void * pointer cannot be dereferenced.
f) float x = 19.34;
float xPtr = &x;
printf( "%f\n", xPtr );
ANS: xPtr is not defined as a pointer, so it should not be assigned the value of &x. Either
define xPtr as a pointer and dereference it in the printf statement in the third line,
or remove the & operator from x in the second line.
g) char *s;
printf( "%s\n", s );
ANS: s has not been assigned a value; it does not point to anything.

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
294 Chapter 7 C Pointers: Solutions

7.26 What does this program do?

1 /* ex07_26.c */
2 /* What does this program do? */
3 #include <stdio.h>
4
5 int mystery3( const char *s1, const char *s2 ); /* prototype */
6
7 int main( void )
8 {
9 char string1[ 80 ]; /* create char array */
10 char string2[ 80 ]; /* create char array */
11
12 printf( "Enter two strings: " );
13 scanf( "%s%s", string1 , string2 );
14 printf( "The result is %d\n", mystery3( string1, string2 ) );
15 return 0; /* indicates successful termination */
16 } /* end main */
17
18 int mystery3( const char *s1, const char *s2 )
19 {
20 for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
21
22 if ( *s1 != *s2 ) {
23 return 0;
24 } /* end if */
25 } /* end for */
26
27 return 1;
28 } /* end function mystery3 */

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Special Section: Building Your Own Computer 295

ANS: The program compares two strings, element by element, for equality.

Enter two strings: string1 string2


The result is 0

Enter two strings: string2 string2


The result is 1

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Вам также может понравиться