Example of C Language Creating Stack Array// Example : create a stack in C language
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// Create a structure to represent the stack
struct Stack {
int top;
unsigned capacity;
int* array;
};
// Create a stack for a given capacity. It initializes the size of the stack to 0
//
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
// When top equals the last index, the stack is full
int isFull(struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}
// Check if the stack is empty
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
// Add an element to the stack (push in stack)
void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
// Pop and return an element at the top of the stack
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
// Returns the top element in the stack, but does not pop the element
int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
// test
int main()
{
struct Stack* stack = createStack(100);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
return 0;
}