In-depth understanding of computer system Second Edition exercise solution Csapp 2.11

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.