我正在解决一个还原数组的作业,在某个时候,经过(显然不相关的)更改之后,代码突然被编译了。
此版本
#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];
答案 0 :(得分:1)
在以下几行中:
int* inverter;
*inverter = *a;
inverter
被声明为指向int
的指针,但是没有指向它的初始地址(内容,即地址,是未定义的)。
应该是:
int inverter;
inverter = *a;
*a = *b;
*b = inverter;