In-depth understanding of computer system second exercise answers CSAPP 2.11, csapp2.11

Source: Internet
Author: User

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

 

Related Article

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.