In-depth understanding of computer system second exercise answers CSAPP 2.11, csapp2.11
Based on the inplace_swap function in 2.10, you decided to write a piece of code to implement the reconciliation between the two ends of an array. You wrote the following function:
1 void reverse_array(int a[], int cnt) 2 { 3 int first, last; 4 for(first = 0, last = cnt - 1; 5 first <= last; 6 first ++, last --) 7 { 8 inplace_swap(&a[first], &a[last]); 9 }10 }
When an array contains 1, 2, 3, and 4, expected results 4, 3, 2, and 1 are obtained. However, when an array containing elements 1, 2, 3, 4, and 5 uses this function, you will be surprised to see the result as 5, 4, 0, 2, and 1. For an array with an even number of elements, an array with an odd number of elements sets the intermediate element to 0.
A. For an array with an odd number, the length is cnt = 2 k + 1. What are the values of the first and last variables in the last loop of the reverse_array function?
B. Why does the inplace_swap call set the array element to 0?
C. Which simple changes can be made to the reverse_array code to eliminate this problem?
Answer:
A. first and last are both k.
B. the last cycle. Assume that a [k] is p.
Procedure |
* X |
* Y |
Initial |
A [k] = p |
A [k] = p |
Step 1 |
0 |
P ^ p = 0 |
Step 2 |
0 |
0 |
Step 3 |
0 |
0 |
C. Change the code of Line 4 to the following.
1 first < last