Here is an example of how you can implement a stack using an array in C:
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int value) {
if (top == MAX_SIZE - 1) {
printf("Error: stack overflow\n");
return;
}
top++;
stack[top] = value;
}
int pop() {
if (top == -1) {
printf("Error: stack is empty\n");
return -1;
}
int value = stack[top];
top--;
return value;
}
int main() {
push(1);
push(2);
push(3);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
return 0;
}
This code defines a stack with a maximum size of 100. The push
function adds a value to the top of the stack, while the pop
function removes and returns the value at the top of the stack. The main
function demonstrates how to use these functions by pushing 3 values onto the stack and then popping them off again.