My stack.h file :
Code:
/* stack using array implementation */
#include <stdio.h>
#include <stdlib.h>
#define max 5
struct stack {
int array[max];
int top;
};
typedef struct stack stack;
int isFull (stack *s);
int isEmpty (stack *s);
void push (stack *s, int value);
void pop (stack *s);
void printStack (stack *s);
My stack.c file :
Code:
/* stack operations */
#include "stack.h"
int isFull (stack *s) {
if (s->top >= max) {
printf("s->top is greater than or equal to max.\n");
return 0;
} else {
return 1;
}
}
int isEmpty (stack *s) {
if (s->top == -1) {
return 0;
} else {
return 1;
}
}
void push (stack *s, int value) {
if (!(isFull(s))) {
printf("Stack overflow.\n");
} else {
s->top++;
s->array[s->top] = value;
}
}
void pop (stack *s) {
if (!(isEmpty(s))) {
printf("The stack is empty.\n");
} else {
printf("The value being popped: %d\n", s->array[s->top--]);
}
}
void printStack (stack *s) {
int i;
if (s->top == -1) {
printf("There is nothing to print.\n");
} else {
printf("s->top : %d\n", s->top);
printf("Stack:\n");
printf("======\n");
for (i=s->top; i>=0; i--) {
printf("%d\n", s->array[i]);
}
}
}
my stackMain.c file :
Code:
/* main file for stack */
#include "stack.h"
int main () {
stack *ptr;
ptr = (stack *) malloc (sizeof(stack));
ptr->top = -1;
push(ptr, 1);
push(ptr, 5);
push(ptr, 8);
push(ptr, 11);
push(ptr, 224);
push(ptr, 9);
pop(ptr);
printStack(ptr);
return 0;
}
After compilation, the result is:
The value being popped: 0
s->top : 8
Stack:
======
0
0
135137
8
224
11
8
5
1
which is really weird, because I have limited the stack to five elements(or I thought I have) (in stack.h, #define max 5). However, the number of stack elements will change according to the last value I pushed onto the stack, in this case, it's 9, i.e. if I change the value of max to 100, the stack will grow to 100 elements.
What did I do wrong?
Thanks.
Regards,
barramundi9