Batteries with sequential allocation

0

I'm having trouble implementing the code in a stack using vectors:

typedef struct pilha pilha;
struct pilha
{

    int *v;
    int topo;
    int tam_max;
};



void Inicializar_Pilha (pilha pi, int tam_max)
{

    pi.v=new int [tam_max];
    pi.topo=-1;
    pi.tam_max=tam_max;
    return;
}

Apparently pi.topo and pi.tam_max is not being stored, but the program runs and then stops responding

    
asked by anonymous 15.09.2017 / 07:21

1 answer

0

The Inicializar_Pilha function should be given a pointer to pilha and not pilha , so that it can change the object it has in main . Soon this function should look like this:

void Inicializar_Pilha (pilha *pi, int tam_max) //agora com * para ser ponteiro
{

    pi->v=new int [tam_max]; //-> em vez de . porque é ponteiro
    pi->topo=-1; //agora com ->
    pi->tam_max=tam_max;//agora com ->
    //return; //return no fim de uma função void não faz sentido
}

And the main something like:

int main(){
    pilha p1;
    Inicializar_Pilha(&p1, 10); //aqui passado com & para ser o endereço do objeto

    cout<<p1.topo<<" "<<p1.tam_max; //-1 10

    return 0;
}

See it working on Ideone

The problem is that since you have in your code the InicializarPilha function receives a copy of the original object it has in main , so changes made to the function are done in a copy and do not affect pilha is in main .

Related reading that I recommend

    
15.09.2017 / 12:40