Search code examples
cstack

Problem with my stack implementation in C


I'm learning Data Structures and was implementing a stack on C. The code compiles correctly but the stack remains unedited i.e. nothing is being pushed into the stack even after a push operation and it stays empty. I'm not sure where the problem with this code is. Please help me with this. Thanks.

Here is my code:

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

#define MAX_SIZE 101 

//Define a struct
struct stack{
    int A[MAX_SIZE]; //Array of size 101
    int top; //Variable that stores the index position of the recently inserted element in the stack.
};

//Function to create a stack, set top to -1 and return it.
struct stack CreateStack(){
    struct stack p;
    p.top = -1;
    return p;
}

//Function to insert a number at the end of the stack.
void Push(int x, struct stack p){

    //If the array is full, return an error message.
    if (p.top == MAX_SIZE - 1){
        printf("Error: Stack Overflow!");
        return;
    }
    
    //Increment top and set insert x at the last of A.
    p.top++;
    p.A[p.top] = x;
};

//Function to delete an element from the last in a stack.
void Pop(struct stack p){

    //If stack is already empty, print a message.
    if (p.top == -1){
        printf("Empty Stack!");
        return;
    }

    //Decrement top. 
    p.top--;
};


//Function to return the top element in the stack.
int Top(struct stack p){
    return p.A[p.top];
};


//Function to check if the stack is empty.
int IsEmpty(struct stack p){
    return p.top == -1;
};


//Function to display all the elements in the stack.
void Print(struct stack p)
{
    printf("Stack: ");
    for(int i = 0; i <= p.top; i++){
        printf("%d", p.A[i]);
    }
    printf("\n");
};


int main(){
    struct stack mystack = CreateStack(); //Creates a stack called mystack.
    Push(22, mystack); //Pushes 22 on the stack.
    Print(mystack);// Should display 22.
}

Solution

  • You pass struct stack p by value (copy); instead pass it in via pointer so the modifying functions can change state:

    void Push(int x, struct stack *p,) {
        if (p->top == MAX_SIZE - 1){
            printf("Error: Stack Overflow!");
            return;
        }
        p->A[p->top++] = x;
    };
    

    It's a convention to pass the abstract data type (here struct stack *p) as the first argument. Also consider returning a status so caller can tell if the function failed. Finally, it's a good idea to separate i/o (printing error messages) from logic, as it may depend on the context of the caller (console/browser/gui, but also it may not be an error for caller if the stack is full). For example:

    struct stack *Push(struct stack *p, int x) {
        if (p->top == MAX_SIZE - 1) return NULL;
        p->A[p->top++] = x;
        return p;
    };