Pass by reference printing garbage in the vector

Asked

Viewed 101 times

4

Guys, I made a simple code, but I have a problem. I made a function "increase" to increase the size of a vector; the function receives the vector and passes the values of that vector to an auxiliary vector. So I can delete the vector, allocate the new size and recover the values of it pq were saved in the aux vector. The problem is that it ta printing trash. If I print the vector inside the function comes out all right but the main goes wrong. Can anyone help? Follow the code:

    #include<iostream>
using namespace std;

void aumentar(int *vetor, int tam){
    int *aux, i;

    aux= new int[tam];

    for(i=0; i<tam; i++){
        aux[i]=vetor[i];
    }

    cout<<"aux:"<<endl;
    for(i=0; i<tam; i++){
        cout<<aux[i]<<" ";
    }
    cout<<endl;

    delete []vetor;

    vetor = new int[11];

    for(i=0; i<tam; i++){
        vetor[i]=aux[i];
    }

    vetor[tam]=10;

    for(i=0; i<11; i++){
        cout<<vetor[i]<<" ";
    }
    cout<<endl;

}

int main(){
    int *vetor, i;

    vetor = new int[10];

    for(i=0; i<10; i++){
        vetor[i]=i;
    }

    for(i=0; i<10; i++){
        cout<<vetor[i]<<" ";
    }
    cout<<endl;

    aumentar(vetor,10);

    cout<<"Resultado"<<endl;

    for(i=0; i<11; i++){
        cout<<vetor[i]<<" ";
    }
    cout<<endl;

}

1 answer

4


void aumentar(int *vetor, int tam)

In this capacity, int *vetor is a pointer passed by copy, and not by reference. It only receives the previously allocated memory value. This means that vetor in function main and vetor in function aumentar are pointing to the same memory address but they are not the even pointer.

When you modify vetor within the function aumentar

delete []vetor;
vetor = new int[11];

it now points to a different place in memory. But this is a variable in the stack; a copy of vetor in function main! vetor is local to the function you are.

What you want is a reference:

void aumentar(int *& vetor, int tam)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.