user13582240
user13582240

Reputation: 13

Tried implementing stack through structure in C but getting Runtime Error for the below code. Can anyone explain and point out as to what went wrong?

Here's an inline link to Github stack_implementation_using_structure

#include <stdio.h>
#define MAXSIZE 5

struct stack
{
    int stk[MAXSIZE];
    int top;
};
typedef struct stack STACK;
STACK s;

void push(int);
void pop(void);
void display(void);

void main ()
{
    s.top = -1;
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    display();
    push(6);
    pop();
    pop();
    pop();
    pop();
    pop();
    pop();
}
/*  Function to add an element to the stack */
void push (int num)
{
    if (s.top == (MAXSIZE - 1))
    {
        printf ("Stack is Full\n");
    }
    else
    {
        s.top++;
        s.stk[s.top] = num;
    }
}
/*  Function to delete an element from the stack */
void pop ()
{
    if (s.top == - 1)
    {
        printf ("Stack is Empty\n");
    }
    else
    {
        printf ("poped element is = %d\n", s.stk[s.top]);
        s.top--;
    }
}
/*  Function to display the status of the stack */
void display ()
{
    int i;
    if (s.top == -1)
    {
        printf ("Stack is empty\n");
    }
    else
    {
        printf ("The status of the stack is \n");
        for (i = s.top; i >= 0; i--)
        {
            printf ("%d ", s.stk[i]);
        }
    }
    printf ("\n");
}

Upvotes: 1

Views: 57

Answers (2)

pierrev
pierrev

Reputation: 1

It worked for me but be careful you're trying to put 6 elements in the stack with an array of 5 elements (with the MAXSIZE at 5). The last one will not be considered and it can create bigger problems.

Upvotes: 0

Ian Abbott
Ian Abbott

Reputation: 17403

The return type of the main function should be int, not void, and for a main with no parameters, the parameter list should be void:

int main (void)
{
    s.top = -1;
    /* ... */
    return 0; // can be omitted - see description below.
}

Although the C standard allows main's execution to reach the end of the function without executing a return statement, I like to add a return 0; for portability with earlier versions of the C standard that did not have this feature.

Upvotes: 0

Related Questions