Passing by reference printing garbage in the vector

4

Personal I made a simple code but I have a problem. I did an "increase" function 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 retrieve the values from it, because they were saved in the aux vector. The problem is he's printing trash. If I print the vector inside the function it leaves everything right but in the main it 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;

}
    
asked by anonymous 05.06.2017 / 06:14

1 answer

4
void aumentar(int *vetor, int tam)

In this function, int *vetor is a pointer passed by copy , 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 same 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 the main function! vetor is local to the function you are in.

What you want is a reference :

void aumentar(int *& vetor, int tam)
    
05.06.2017 / 13:43