Find the error in each of the following program segments. Assume the following declara- tions and statements:

```
int *zPtr; // zPtr will reference array z
void *sPtr = 0;
int number;
int z[ 5 ] = { 1, 2, 3, 4, 5 };
```

a) ++zPtr;
b) // use pointer to get first value of array
number = zPtr;
c) // assign array element 2 (the value 3) to number
number = *zPtr[ 2 ];
d) // print entire array z
for ( int i = 0; i <= 5; i++ )
cout << zPtr[ i ] << endl;
e) // assign the value pointed to by sPtr to number
number = *sPtr;
f) ++z;


a) ++zPtr;
ANS: Error: zPtr has not been initialized.
Correction: Initialize zPtr with zPtr = z;
b) // use pointer to get first value of array
number = zPtr;
ANS: Error: The pointer is not dereferenced.
Correction: Change the statement to number = *zPtr;
c) // assign array element 2 (the value 3) to number
number = *zPtr[ 2 ];
ANS: Error: zPtr[ 2 ] is not a pointer and should not be dereferenced.
Correction: Change *zPtr[ 2 ] to zPtr[ 2 ].
d) // print entire array z
for ( int i = 0; i <= 5; i++ )
cout << zPtr[ i ] << endl;
ANS: Error: Referring to an array element outside the array bounds with pointer subscripting. Correction: To prevent this, change the relational operator in the for statement to <.
e) // assign the value pointed to by sPtr to number
number = *sPtr;
ANS: Error: Dereferencing a void pointer.
Correction: To dereference the void pointer, it must first be cast to an integer pointer. Change the statement to number = *static_cast< int * >( sPtr );
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 pointer arithmetic, or subscript the array name to refer to a specific element.

Computer Science & Information Technology

You might also like to view...

Function syntax refers to the placement of arguments within a function

Indicate whether the statement is true or false

Computer Science & Information Technology

The longer a customer stays on a Web site, the more attractive that Web site is to advertisers.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

Draw thr graphs whose weight matrices are


7
Also comment on graph types.

Computer Science & Information Technology

Case-Based Critical Thinking QuestionsCase 9-2Let's Camp is a camping supply shop that sells new camping equipment to hip urban teens and young adults. The Web developer, Sally, wants the pages to be designed for use on cell phones and other handheld devices their young audiences carry. Which element should Sally not use in her Web pages to avoid violating the strict DTD rules?

A. body B. img C. font D. span

Computer Science & Information Technology