I have improved on several things, among them I simplified the parameter passing, do not need to pass pointer pointer. But the main error is that the >=
operator could not be used in while
. When it reaches 0 it has to stop, because of =
it did one more operation. But there is also a problem on the other side. It starts by taking the index equivalent to the amount of elements in the stack. As index begins at 0, the last one is minus 1. With these two changes it works. But it's still not releasing memory (I know it's unnecessary in this example, but it's good to get used to doing right every time):
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
typedef struct pilha {
int qnt;
int dados[MAX];
} Pilha;
Pilha* cria() {
Pilha *p = malloc(sizeof(Pilha));
if (p != NULL) {
p->qnt = 0;
}
return p;
}
void insere(Pilha *p, int valor) {
p->dados[p->qnt] = valor;
p->qnt++;
}
void exibe(Pilha *p) {
for (int i = 0; i < p->qnt; i++)
printf("%3d", p->dados[i]);
}
Pilha* inverte(Pilha *p) {
Pilha *outra = cria();
while (p->qnt > 0) {
outra->dados[outra->qnt] = p->dados[p->qnt - 1];
p->qnt--;
outra->qnt++;
}
return outra;
}
int main() {
Pilha *p = cria();
insere(p, 32);
insere(p, 45);
insere(p, 78);
exibe(p);
p = inverte(p);
printf("\n");
exibe(p);
}
See working on ideone and on Coding Ground >.