0
I need to make a stack that does a push, pop and print. So I created the functions and this works. But I wanted to add a String to my stack. Possibly a number and time or just a string. But I can’t get either. Could someone help me, please?
#include <stdio.h>
#define MAXSIZE 5
struct pilha
{
int pilhaa[MAXSIZE];
int top;
};
typedef struct pilha PILHA;
PILHA p;
void push(void);
int pop(void);
void display(void);
void main ()
{
int escolha;
int opcao = 1;
p.top = -1;
printf ("Operacoes da Pilha\n");
while (opcao)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
printf ("Escolha uma opcao!\n");
scanf ("%d", &escolha);
switch (escolha)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return;
}
fflush (stdin);
printf ("(Digite 0 para 'SAIR' ou 1 para 'CONTINUAR')?\n");
scanf ("%d", &opcao);
}
}
/* Função para adicionar um elemento à pilha */
void push()
{
char value[20];
if (p.top == (MAXSIZE - 1))
{
printf ("Pilha Cheia!\n");
return;
}
else
{
printf ("Digite o numero no formato INTEIRO \n");
scanf ("%s", value);
p.top = p.top + 1;
p.pilhaa[p.top] = value;
}
return;
}
/* Função para excluir um elemento da pilha */
int pop()
{
int num;
if (p.top == - 1)
{
printf ("Pilha Vazia!\n");
return (p.top);
}
else
{
num = p.pilhaa[p.top];
printf ("Elemento a ser retirado eh: = %d\n", p.pilhaa[p.top]);
p.top = p.top - 1;
}
return(num);
}
/* Função para exibir o status da pilha */
void display()
{
int i;
if (p.top == -1)
{
printf ("Pilha Vazia\n");
return;
}
else
{
printf ("\n Os status da pilha é: \n");
for (i = p.top; i >= 0; i--)
{
printf ("%s", p.pilhaa[i]);
}
}
printf ("\n");
}
But is the stack supposed to have strings or numbers? It seems that in some situations it is trying to use one and the other
– Isac
At first I did using whole. Then I changed only the stack (push) to string.. But I stuck and posted here to see if someone gives me a light.
– spw
But is it to be with numbers or strings ? With numbers is easier
– Isac
In C if you declare an array of one type, you cannot store another type in the array. There are a few ways around this, one of which would be to have a void* array BUT this is NOT good practice and can give you a lot of headache. You would like to have a stack of strings only?
– prmottajr