Kuljeet
Kuljeet

Reputation: 19

Implementing stack using data structures in C

I'm trying to implement multiple stacks using data structures in C. The issue is that I'm unable to do it from the main() function itself.

I created a custom structure called "stk" which includes an integer array, a[20] and top. Now, I create a variable 's' by writing "stk s" in main function. Then, I use "s.top = -1" to initialize "top" to -1. But, as soon as I use push function, the top is incremented only once i.e. it reaches 0 and it remains at zero no matter how many times I push. I believe that the reason is as I have declared 's' as a local variable in main() and not a global variable, and, push function is of type void, so it is stopping further increment in top. But, if I declare it as a global variable, everything works fine, but again, doing this will limit me to only one stack because now, I have to specify 's' inside of push function, as it'll not accept any arbitrary value.

typedef struct
{
    int a[20];
    int top;
}stk;

stk s; 

void push(int x) //It'll only work for one stack i.e. "s"
{
    s.top++; 
    s.a[s.top] = x; 
}

int main()
{
    //I intend to declare "stk s, t" here
    s.top = -1;
}

Is there any way that I can use the same structure to create a different stack, let's say "stk t", but for that, I need to declare it inside main as two different variables as "stk s, t" and then push using pass-by-value?

Upvotes: 0

Views: 703

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

Provide the stk to the functions via pointer. This requires changing push, for example, to this:

typedef struct
{
    int a[20];
    int top;
} stk;

void push(stk *s, int x)
{
    ++s->top
    s->a[s.top] = x; 
}

stk gs; // global

int main()
{
    gs.top = -1;

    stk s; // local
    s.top = -1;

    // push 42 on the local stack
    push(&s, 42);

    // push 1 on the global stack
    push(&gs, 1);
}

I leave the job of putting boundary checks to avoid overflow, and perhaps a more concise method of initialization, to you. But that's how the same functions can modify different stacks.

Upvotes: 1

Related Questions