How to implement stack in C programming ?

In continuation of demonstrating simple implementation of data structures, as we shown in our last post “How to implement linked list in C programming ?”, in this post we will show how you can implement simple stack in C programming language. Stack is nothing but a one this kept on another, where we define how many maximum elements can be kept in one stack and what is the current size of the stack.

 $ vim simple_stack.c 
[java] #include <stdio.h> #include <stdlib.h> struct stack { int top; int max_elements_in_stack; int *array; }; void push(struct stack *s, int value) { s->top = ++s->top; s->array[s->top] = value; } int pop(struct stack *s) { int val = s->array[s->top]; s->top = –s->top; return val; } struct stack *init_stack(int count) { struct stack *s = (struct stack *)malloc(sizeof(struct stack)); s->top = -1; s->max_elements_in_stack = count; s->array = (int *) malloc(sizeof(int) * count); } int main(int argc, char **argv) { int max_elements_in_stack = 100; struct stack *st = init_stack(max_elements_in_stack); push(st, 10); push(st, 20); push(st, 30); push(st, 40); printf("popped value is %d\n", pop(st)); printf("popped value is %d\n", pop(st)); return 0; } [/java]

The above program, implements simple stack which holds maximum 100 elements and we initialise this stack with “init_stack” and simple function “push” adds an element into stack and pop removes an element from stack [ here stack is just a simple array of integers]

We can compile the program as,

 $ gcc -o simple_stack simple_stack.c 
 $ ./simple_stack 
popped value is 40
popped value is 30

Leave a Comment