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
}