I'm actually facing some weird issue while coding for university project.
I've implemented a stack struct, and trying to make basic functions to manipulate it.
typedef struct _stack {
unsigned int max_capacity;
int* array;
int top_position;
} stack;
int isFull(stack* s){
return s->top_position >= (s->max_capacity - 1);
}
int isEmpty(stack* s){
return s->top_position == -1;
}
void push(stack* s, int elt){
if (isFull(s)) return;
s->array[++s->top_position] = elt;
}
int pop(stack* s){
return s->array[s->top_position--];
}
int peek(stack* s){
return s->array[s->top_position];
}
stack* createStack(unsigned int capacity){
stack* s = malloc(sizeof(stack));
s->max_capacity = capacity;
s->array = malloc(sizeof(int) * capacity);
s->top_position = -1;
return s;
}
But when I try to test it, I got akward results :
stack* s = createStack(5);
if(isFull(s)) printf("Stack full.\n");
printf("Stack top position : %d, stack capacity : %d\n", s->top_position, s->max_capacity);
printf("-1 >= 4 : %d\n", -1 >= 4);
printf("top position >= (capacity - 1) : %d\n", s->top_position >= (s->max_capacity - 1));
returning
Stack full.
Stack top position : -1, stack capacity : 5
-1 >= 4 : 0
top position >= (capacity - 1) : 1
I don't understand the reason why my function isFull is returning a non-zero value when instantiating a new stack.
I put a strict-equality condition instead of greater-or-equal, and now it's working fine, but I need to understand the deep reason of my mistake, can you help me and explain me why the first version wasn't working ?
Thanks.
EDIT: This question is not really a duplicate of the answer linked in comment. Actually I didn't figured that I was comparing signed and unsigned values.