Benuck
Benuck

Reputation: 19

Why changing this array's value, in a function using pointers, is wrong?

I was solving a revert array homework and, at some point, the code compiled, suddenly, after an (apparently unrelated) alteration, the code couldn't be compiled anymore.

This one compiles

#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;
}

This one gives Bus error:10 issue:

#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;
}

Why this 2 lines changes the outcome?

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

Upvotes: 0

Views: 36

Answers (1)

Aviv Goll
Aviv Goll

Reputation: 300

In the following lines:

     int* inverter;
     *inverter = *a;

inverter is declared as a pointer to int but there is no initial address to which it points (the content, i.e address, is undefined).

Should be:

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

Upvotes: 1

Related Questions