Vedant Matanhelia
Vedant Matanhelia

Reputation: 21

C - No output in the program

I made a stack and i am using the isEmpty function but the output is not coming. I trued manually using the gcc command and also using the code runner extension. Here is the code:

#include <stdio.h>
#include <stdlib.h>

typedef struct Stack
{
    int top;
    int size;
    int *arr;
} Stack;

int isEmpty(Stack *st)
{
    if (st->top == -1)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

int main()
{
    Stack *st;
    st->top = -1;
    st->size = 10;
    st->arr = (int *)malloc(st->size * sizeof(int));
    int i = isEmpty(st);
    if (i == 1)
    {
        printf("The stack is empty\n");
    }
    else
    {
        printf("The stack is not empty\n");
    }
    return 0;
}

The file is named Stack.c. There is one more thing that the basic hello world program is working perfectly

Upvotes: 1

Views: 213

Answers (1)

a.koptan
a.koptan

Reputation: 1247

Stack *st;
st->top = -1;

You invoked undefined behavior by accessing uninitialized pointer st->top = -1;.

You should initialize st first:

Stack *st = malloc(sizeof(Stack));

Upvotes: 7

Related Questions