Search code examples
cstructstackpass-by-referencepass-by-value

struct not holding new values


I am making a stack using struct in C, I ran this in the gcc debugger and noticed that in the push() function after providing the value of 'ele' the arr[0] is set to 'ele' and 'top' becomes 0.

But as soon as I exit out of push() the arr[0] is going back again to garbage value and top is becoming -1. Why is that happening. How to make arr[0] hold its value I am providing and top to remain 0.

#include <stdio.h>

#define MAX 10

typedef struct
{
    int top;
    int arr[MAX];
    int ele;

} STACK;

void push(STACK st)
{
    printf("Enter element ");
    scanf("%d", &st.ele);
    if (!isFull(st))
    {
        st.arr[++(st.top)] = st.ele;
    }
    else
    {
        printf("****Stack is full****\n");
    }
}


int main()
{
    STACK st;
    st.top = -1;
    int choice;
    for (;;)
    {
        printf("Stack elements : \n");
        printf("Enter choice \n");
        printf("1.Push\n2.Pop\n3.Display\n4.Peek Top element\n");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            push(st);
            break;
        }
    }
    return 0;
}


Solution

  • For starters the data member ele is redundant in this structure definition

    typedef struct
    {
        int top;
        int arr[MAX];
        int ele;
    
    } STACK;
    

    Define the structure like

    typedef struct
    {
        int top;
        int arr[MAX];
    } STACK;
    

    The function push accepts its argument by value

    void push(STACK st)
    

    It means that the function deals with a copy of the original argument. Changing the copy does not influence on the original object used as an argument.

    You need to pass the original object of the structure type by reference.

    In C passing by reference means passing an object indirectly through a pointer to it.

    Moreover within the function you need at first to check whether the stack is full before entering a new value.

    So the function should be declared and defined the following way

    void push( STACK *st )
    {
        if (!isFull( st))
        {
            printf("Enter element ");
        
            int ele;
    
            if ( scanf("%d", &ele ) == 1 )
            {
                st->arr[++(st->top)] = ele;
            }
            else
            {
                puts( "****i/o error occured****" );
            }
        }
        else
        {
            printf("****Stack is full****\n");
        }
    }
    

    Within the function you need to wirte

    st->arr[++(st->top)] = ele;
    

    And the function is called like

    push( &st );
    

    Pay attention to that the function isFull in turn should be declared like

    int isFull( const STACK *st );