I tried to make a stack push pop operations with storing values from pop in an array. I have a few questions for this code.
1. Does the initialization part work well? When compiling, it seems there is no problem but I'm still curious.
2. Does the deletion part also work well? Although, I typed !
, it seems it doesn't goes to else if(strcmp (str[i], "!")==0)
part.
3. How could store values after pop operations? I want to store it as an array format but when I print out after storing them in the array, runtime error occured.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stack *Stack;
struct stack {
char *array;
int size;
int top;
};//making stack
Stack create(int c);
Stack makeEmpty(void);//initialization
int isEmpty(Stack S)
{
if(S->top==-1)
return 0;
else
return 1;
};
void push(char X, Stack S)
{
S->array[++S->top]=X;
};
char pop(Stack S)
{
return S->array[S->top--];
};
void deleteStack(Stack S)
{
while (S->top>=0)
{
free(S->array[S->top]);
S->top--;
}
};
int main (void)
{
Stack S1=makeEmpty();
char input[100], result[30], result1;
char *word;
int cnt=0,cnt2=0, temp=0, k=0, i,j,l;
word=strtok(input, " ");
char *str[20];
while(1){
if(fgets(input,100,stdin)){
word=strtok(input, " ");//get input and tokenize
cnt=0;
while (word!=NULL)
{
str[cnt]=strdup(word);
cnt++;
word=strtok(NULL," ");
}
}
for (i=0; i<cnt; i++)
{
if (strcmp(str[i],"(")==0 && (isEmpty(S1)==0))
{
push(str[i],S1);
l++;
}
else if(strcmp(str[i],")")==0)
{
temp++;
for(j=0; j<cnt2; j++)
{
char result1=pop(S1);
result[k] =result1;
printf("%s ", result[k]);//This the place where I got runtime error
k++;
}
pop(S1);
cnt2=0;
}
else if(strcmp (str[i], "!")==0)
{
printf("in\n");
deleteStack(S1);
return 0;
}
else
{
if (isEmpty(S1)==1)
{
if (l!=0)
{
push(str[i],S1);
if (strcmp(str[i],"(")!=0)
{
cnt2++;
}
}
}
}
}
}
return 0;
}
Stack create(int c)
{
Stack S=(Stack)malloc(sizeof(struct stack));
S->size=c;
S->top=-1;
S->array=(char *)malloc(sizeof(char)*c);
return S;
}
Stack makeEmpty(void)
{
Stack S1=create(100);
S1[0].top=-1;
return S1;
}