深入理解计算机系统 练习题2.11 答案与分析

可执行代码

#include <stdio.h>  
#include "stdafx.h"
#include <iostream>

using namespace std;
void inplace_swap(int *x, int *y) {
    *y = *x ^ *y;
    *x = *x ^ *y;
    *y = *x ^ *y;

}

void reverse_array(int a[],int cnt) {
    int first, last;
    for (first = 0,last = cnt - 1 ;first <= last; first++,last--)
    {
        inplace_swap(&a[first], &a[last]);
    }
}

int main() {
    int a[] = {1,2,3,4,5};
    int len = sizeof(a) / sizeof(int);
    reverse_array(a, len);
    for (int i = 0; i<len; i++)
    {
        cout << a[i] <<",";
    }
    cout << endl;
    int b[] = { 1,2,3,4 };
    int len2 = sizeof(b) / sizeof(int);
    reverse_array(b, len2);
    for (int i = 0; i<len2; i++)
    {
        cout << b[i] << ",";
    }
    cout << endl;
    system("pause");
}

结果演示
这里写图片描述
A.对于一个长度为技术的数组,长度cnt=2k+1,函数reverse_array最后一次的循环中,变量first和last的值分别是什么
根据示例代码int a[] = {1,2,3,4,5};来进行讲解,此时变量为
咱们一步一步分析

  1. 第一次inplace_swap时len = 5,first = 0,last = 4,所以执行inplace_swap表示a[0]与a[4]交换,交换后数组a为[5,2,3,4,1]
  2. 第二次inplace_swap时由于first++,last–,所以first = 1,last = 3,所以执行inplace_swap表示a[1]与a[3]交换,交换后数组为[5,4,3,2,1]
  3. 第三次inplace_swap时由于first++,last–,所以first = 2, last = 2,所以执行inplace_swap表示a[2]与a[2]交换,出现问题的过程不是交换,而是inplace_swap方法,我们来看看inplace_swap方法。
void inplace_swap(int *x, int *y) {
    *y = *x ^ *y;
    *x = *x ^ *y;
    *y = *x ^ *y;

}

此时inplace_swap(&a[first], &a[last]);传递的参数是什么呢?

inplace_swap(&a[2], &a[2]);

因为我们传送的是指针,所以现在我们int *x, int *y这两个变量指向的是同一个变量,知道了这个我们将变量替换进去后继续分析。

  1. 第一步*y = *x ^ *y; 替换之后a[2] = a[2] ^ a[2] =0;
  2. 第二步*x = *x ^ *y; 替换之后a[2] = 0 ^ 0 =0;
  3. 第二步*y = *x ^ *y; 替换之后a[2] = 0 ^ 0 =0;

也就是图上所示结果
B.为什么这时调用函数inplace_swap会将数组元素设置为0?
上面已经讲的很清楚,这里不再解释
C.对reverse_array的代码做哪些简单改动就能消除这个问题?
修改很简单,就是把first <= last;改为first < last;

#include <stdio.h>  
#include "stdafx.h"
#include <iostream>

using namespace std;
void inplace_swap(int *x, int *y) {
    *y = *x ^ *y;
    *x = *x ^ *y;
    *y = *x ^ *y;

}

void reverse_array(int a[],int cnt) {
    int first, last;
    for (first = 0,last = cnt - 1 ;first < last; first++,last--)
    {
        inplace_swap(&a[first], &a[last]);
    }
}

int main() {
    int a[] = {1,2,3,4,5};
    int len = sizeof(a) / sizeof(int);
    reverse_array(a, len);
    for (int i = 0; i<len; i++)
    {
        cout << a[i] <<",";
    }
    cout << endl;
    int b[] = { 1,2,3,4 };
    int len2 = sizeof(b) / sizeof(int);
    reverse_array(b, len2);
    for (int i = 0; i<len2; i++)
    {
        cout << b[i] << ",";
    }
    cout << endl;
    system("pause");
}

猜你喜欢

转载自blog.csdn.net/ciqingloveless/article/details/82690978