Search code examples
cstructstack

I'm trying to create a stack in c using structures but my push function doesn't work


I'm trying to create a stack in C using structures but the push() function I wrote is acting strangely. I'm sure it is something obvious that I'm missing but I just couldn't figure out what.

#include <stdio.h>

#define STACK_SIZE 50

typedef struct stack
{
    int top;
    int items[STACK_SIZE];
}
STACK;

void push(STACK* st, int newitem)
{
    st->top++;
    st->items[st->top] = newitem;
    printf("%d", st->items[st->top]);
}


int main()
{
    int n = 1;
    STACK* st;

    printf("test 1\n");
    
    st->top = -1;

    push(st, n);
    
    printf("test 2\n");
    
    return 0;
}

DevCpp only compiles but doesn't execute the code. OnlineGDB runs it but only prints the first test.


Solution

  • This is because your variable STACK* st; was never initialized properly.

    Some Important Points:

    • Don't assign -1 to the length (top), 0 would be better
    • STACK* st; should be just STACK st;
    • Your function void push(STACK* st, int newitem) should be declared with static linkage.
    • Write st->top++
    • Pass st variable by address to the push() function
    • Instead of using bare return 0;, use return EXIT_SUCCESS;, which is defined in the header file stdlib.h.
    • As your total STACK_SIZE is only 50 so, int will be sufficient. But as your STACK_SIZE grows use size_t for your length(top).
    • use int main(void) { }, instead of int main() { }
    • NOTE: If STACK_SIZE and top becomes equal means your array is filled completely then further addition of data will lead to Undefined Behavior.

    Final Code

    #include <stdio.h>
    #include <stdlib.h>
    
    #define STACK_SIZE 50
    
    typedef struct stack
    {
        int top;
        int items[STACK_SIZE];
    }
    STACK;
    
    static void push(STACK* st, int newitem)
    {
        if(st->top == STACK_SIZE)
        {
            fprintf(stderr, "stack size reached maximum length\n");
            exit(EXIT_FAILURE);
        }
        st->items[st->top++] = newitem;
        printf("%d\n", st->items[st->top - 1]); // we added +1 to `top` in the above line
    }
    
    
    int main(void)
    {
        int n = 1;
        STACK st;
        printf("test 1\n");
        st.top = 0;
        push(&st, n); //pass by address
    
        return EXIT_SUCCESS;
    }