CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Removing items from our stack data structure

The function pop_item now removes an item from the stack, and returns the actual data's value.

In this example, the data held in each STACKITEM is just a single integer, but it could involve several fields of data. In that case, we may need more complex functions to return all of the data (perhaps using a structure or pass-by-reference parameters to the pop_item function).

Again, we must ensure that we don't attempt to remove (pop) an item from an empty stack:


int pop_item(void)
{
    STACKITEM  *old;
    int        oldvalue;

    if(stack == NULL) {
        fprintf(stderr, "attempt to pop from an empty stack\n");  
        exit(EXIT_FAILURE);
    }

    oldvalue     = stack->value;
    old          = stack;
    stack        = stack->next;
    free(old);

    return oldvalue;
}

 


CITS2002 Systems Programming, Lecture 19, p4, 3rd October 2023.