Stacks with sequential allocation

Asked

Viewed 90 times

0

I’m having problems implementing the code of 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

1 answer

0


The function Inicializar_Pilha shall receive a pointer to pilha and not pilha, so that you can change the object you have in main. So that role should be 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;
}

Watch it work on Ideone

The problem is that as it has in its code the function InicializarPilha receives a copy of the original object in the main, and so the changes made to the function are made in a copy and do not affect the pilha who is in the main.

Related reading that I recommend

Browser other questions tagged

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