On the basis of the Inplace_swap function in 2.10, you decide to write a piece of code that will swap the ends of an array of elements in turn, and you write the following function:
1 voidReverse_array (intA[],intCNT)2 {3 intFirst , last;4 for(First =0, last = cnt-1;5First <=Last ;6First + +, last--)7 {8Inplace_swap (&a[first], &A[last]);9 }Ten}
When the array contains 1, 2, 3, 4 o'clock, the expected results are 4, 3, 2, 1. However, when you use this function with an array containing elements of 1, 2, 3, 4, 5, you will be surprised to see results of 5, 4, 0, 2, 1. For arrays of an even number of elements to work correctly, an array of odd elements sets the intermediate element to 0.
A. For an array of odd length, cnt = 2k + 1, function Reverse_array What are the values for the first and last of the variables, respectively?
B. Why does calling the function Inplace_swap set the array element to 0?
C. What simple changes can be made to Reverse_array code to eliminate this problem?
Answer:
A. Both first and last are K.
B. When the last cycle occurs. Suppose A[k] is p.
| Steps |
*x |
*y |
| Initial |
A[k]=p |
A[k]=p |
| The first step |
0 |
P^p=0 |
| Step Two |
0 |
0 |
| Step Three |
0 |
0 |
C. Change the 5th line of code to the following.
1 First < last
In-depth understanding of computer system Second Edition exercise solution Csapp 2.11