The error is found in this excerpt:
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 increasing the value of the pointer and afterward applying the dereference operator * (see the precedence of operators). Thus, the value top is never incremented.
To express, in fact, what you want, you must use (*topo)++. Thus, you deselect the pointer and then increment the value pointed by it.
Note that the error also occurs in the pop-up 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 value top, use the expression (*topo)--.
There is yet another error in the code posted. The functions empilha(int *p[], int *topo, int valor) and desempilha(int *p[], int *topo) request as first parameter a pointer to an array, which could be written as int **p.
However, within the method main, you are passing as argument for these functions the variable int pilha[], which is an array, ie an int *.
You must change the arguments int *p[] for int p[] (or int *p), in addition to changing the function return expression desempilha for return p[*topo]; for compliance with the previous change.
Finally, note that the function formatting character printf below should be %d, nay &d.
for (i=0; i<10; i++)
{
printf("&d\n", desempilha(pilha, &topo)); // ao invés de &d, o correto é %d
}
Opa thanks, but here it did not work, I put the parentheses in top-- and top++ and ran the program, gave a Windows error ("... Stopped working - debug or close program".
– André
Note that its functions
empilha()anddesempilhaexpect a parameterint *p[], that is, a pointer to a vector, and you’re passing them a vector (and treating it as a vector in the function body). Try saying(int p[], ...– Wtrmute
Besides, you also need to say
return p[*topo];in place ofreturn *p[*topo];to avoid reading random memory addresses– Wtrmute
@Wtrmute added the information regarding this other problem in the answer.
– Gabriel Faria
I switched the int arguments *p[] to int p[] I took the pointers before p and the result was '&d' below each other 10 times.
– André
Maybe it’s because the right one is %d and not &d.
– Gabriel Faria