developers! I have a question of push() method of the stack in C!
I implemented my own push() method in C! but I can't understand the results!
My stack code below
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
int top = -1;
int array[MAX_SIZE];
void init(){
top = -1;
}
void push(int array[], int data){
if(top > MAX_SIZE-1)
fprintf(stderr, "invalid top %d\n", top+1);
else{
array[++top] = data; // top == 9, ++top == 10
printf("top: %d data: %d\n", top+1, array[top]); // top == 11, top == 10
}
}
void pop(int array[]){
}
void peek(int array[]){
}
int main() {
int data = 1;
for (int i=0; i<MAX_SIZE; i++)
push(array, data++);
push(array, 100);
push(array, 200); // invalid top
push(array, 300); // invalid top
return 0;
}
and the result of this code is below
top: 1 data: 1
top: 2 data: 2
top: 3 data: 3
top: 4 data: 4
top: 5 data: 5
top: 6 data: 6
top: 7 data: 7
top: 8 data: 8
top: 9 data: 9
top: 10 data: 10
top: 11 data: 100
invalid top 11
invalid top 11
The thing That I don't understand is .. in the results, when top: 11, actually, it's like top: top+1. If you look into the else statement in my push() method, you can notice it.
but, in else statement, when
printf("top: %d data: %d\n", 11, array[10]);
the result: top: 11 data: 100
, I think it should be an error. because I declared array size as 10 which is MAX_SIZE. so the index size will be 0 ~ 9. but how could array[10] works??
I really don't understand it.