Implementation of Stack Using Arrays in C
In the array-based implementation of a stack, we use an array to store the stack elements. The top of the stack is represented by the end of the array. Hence, we keep an index pointer named top. We can also enclose this array and index pointer in the structure data type.
Representation of Array Stack in C
typedef struct stack {
int top;
int capacity;
type* arr;
}Stack;
Here, we typedef is used for convenience for shorter struct declaration. It is recommended to define the array as the last element as to avoid overwriting the top variable in case of out of bound writing of array. We can define the size of the array dynamically using desired value.
Initially, we set the top index pointer to -1 representing there are no elements in the stack. We can then implement the basic stack operation according to this representation.
The below illustration shows the working of array stack in C:
Implementation of Stack Using Array in C
A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the most recently added element is the first one to be removed. In this article, we will learn how to implement a stack using an array in C.