为什么在使用指针的函数中更改此数组的值是错误的?

时间:2019-05-22 04:15:55

标签: c arrays function pointers reference

我正在解决一个还原数组的作业,在某个时候,经过(显然不相关的)更改之后,代码突然被编译了。

此版本

#include <iostream>
#define MAX 100
#define fori(x, y) for(int i = x; i<y; i++)
using namespace std;

int vetor[MAX];

void inverterElemento(int* a, int* b){
     int* inverter;
     *inverter = *a;
     *a = *b;
     *b = *inverter;
}

int main(){
    for (int i = 0; i < MAX; i++){
        vetor[i] = 7*i;
    }
    for (int k = 0; k <= MAX/2; k++){
        int a = vetor[k];
        int b = vetor[MAX-k-1];
        inverterElemento(&vetor[k], &vetor[MAX - k - 1]);
    }
    fori(0, MAX) cout << vetor[i] << " "; cout << endl;
    return 0;
}

这是Bus error:10的问题:

#include <iostream>
#define MAX 100
#define fori(x, y) for(int i = x; i<y; i++)
using namespace std;

int vetor[MAX];

void inverterElemento(int* a, int* b){
     int* inverter;
     *inverter = *a;
     *a = *b;
     *b = *inverter;
}

int main(){
    for (int i = 0; i < MAX; i++){
        vetor[i] = 7*i;
    }
    for (int k = 0; k <= MAX/2; k++){

        inverterElemento(&vetor[k], &vetor[MAX - k - 1]);
    }
    fori(0, MAX) cout << vetor[i] << " "; cout << endl;
    return 0;
}

为什么这两行会改变结果?

int a = vetor[k];
int b = vetor[MAX-k-1];

1 个答案:

答案 0 :(得分:1)

在以下几行中:

     int* inverter;
     *inverter = *a;

inverter被声明为指向int的指针,但是没有指向它的初始地址(内容,即地址,是未定义的)。

应该是:

    int inverter;
    inverter = *a;
    *a = *b;
    *b = inverter;