Code stacking and unstacking a stack

1

I'm testing this code in codeblocks and it's giving a very strange result, saying the stack is empty and I can not see where the error is.

void empilha (int *p[], int *topo, int valor){
    if (*topo<10)
    {
        p[*topo] = valor;
        *topo++;
    }
    else
        printf ("Pilha cheia!");
}

int desempilha (int *p[], int *topo){
    if (*topo>0)
    {
        *topo--;
        return *p[*topo];
    }
    else
        printf("Pilha vazia!");
}


int main() {

    int pilha[10], topo=0;
    int i, valor=1020;
    for (i=0; i<10; i++)
    {
        empilha(pilha, &topo, valor);
        valor = valor + i;
    }

    for (i=0; i<10; i++)
    {
        printf("&d\n", desempilha(pilha, &topo));
    }
}
    
asked by anonymous 09.03.2017 / 16:24

1 answer

5

The error is in this section:

void empilha (int *p[], int *topo, int valor) {
    if (*topo<10)
    {
        p[*topo] = valor;
        *topo++; // note essa declaração
    }
    else
        printf ("Pilha cheia!");
}

When you have the expression *topo++ , you are actually incrementing the value of the pointer and after by applying the dereference operator * (see Operator Precedence) . This way, the top value is never increased.

To actually express what you want, you should use (*topo)++ . Thus, you dereferentiate the pointer and then increment the value pointed to by it.

Note that the error also occurs in the peel function:

int desempilha (int *p[], int *topo){
    if (*topo>0)
    {
        *topo--; // aqui, o ponteiro é decrementado antes da desreferência
        return *p[*topo];
    }
    else
    printf("Pilha vazia!");
}

In this case, to decrease the top value , use the expression (*topo)-- .

There is yet another error in the posted code. The empilha(int *p[], int *topo, int valor) and desempilha(int *p[], int *topo) functions ask as a first parameter a pointer to an array, which could be written as int **p .

However, within the main method, you are passing as an argument to these functions the int pilha[] variable, which is an array, that is, int * .

You should change the arguments int *p[] to int p[] (or int *p ), and change the return expression of the function desempilha to return p[*topo]; to conform to the previous change.

Finally, note that the formatting character of the printf function below should be %d , not &d .

for (i=0; i<10; i++)
{
    printf("&d\n", desempilha(pilha, &topo)); // ao invés de &d, o correto é %d
}
    
09.03.2017 / 18:50