I am trying to write a code to depict all the basic operations of stack, but as soon as I compile my code and run it. It immediately stops working.
I am getting no compilation error in my IDE (CodeBlocks). How do I know what is the error in my code?
Can I also somehow change the settings in CodeBlocks so as to also display such runtime errors?
What is the error in my code below? Is it the use of the arrow operator (->) one after the other? Thank You.
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *prev;
}node;
typedef struct stack
{
node *top;
}stack;
int count=0;
void push(stack *x, int num)
{
node *temp;
if(x->top == NULL)
{
temp=(node *)malloc(sizeof(node *));
temp->data=num;
temp->prev=NULL;
x->top=temp;
}
else
{
temp=(node *)malloc(sizeof(node *));
temp->data=num;
temp->prev=x->top;
x->top=temp;
}
count++;
return;
}
int pop(stack *x)
{
node *temp;
int m;
if(x->top == NULL)
{
printf("Error:The stack is empty\n");
return;
}
else
{
m=(x->top)->data;
temp=(x->top)->prev;
x->top=temp;
}
count--;
return m;
}
int main()
{
int k=1, n, num;
stack *myStack;
myStack->top = NULL;
while(k)
{
printf("Enter the operation you want to perform\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.TOP\n");
printf("4.STACK COUNT\n");
scanf("%d", &n);
switch(n)
{
case 1:
printf("Enter the number you want to push to the stack\n");
scanf("%d", &num);
push(myStack, num);
break;
case 2:
printf("The popped element is %d\n", pop(myStack));
break;
case 3:
printf("The topmost element of the stack is %d\n", (myStack->top)->data);
break;
case 4:
printf("The number of elements in the stack are %d\n", count);
break;
default:
printf("Invalid request\n");
break;
}
printf("Do you wish to perform another operation?(1/0)");
scanf("%d", &k);
}
return 0;
}