【发布时间】:2018-06-10 08:06:23
【问题描述】:
开发者! 我对 C 中堆栈的 push() 方法有疑问!
我在 C 中实现了自己的 push() 方法! 但我无法理解结果!
下面是我的堆栈代码
#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;
}
这段代码的结果如下
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
我不明白的是.. 结果,当 top: 11 时,实际上就像 top: top+1。 如果您查看我的 push() 方法中的 else 语句,您会注意到它。
但是,在 else 语句中, 当
printf("top: %d data: %d\n", 11, array[10]);
the result: top: 11 data: 100
,我认为这应该是一个错误。因为我将数组大小声明为 10,即 MAX_SIZE。所以索引大小将是 0 ~ 9。 但是 array[10] 怎么工作??
我真的不明白。
【问题讨论】:
-
C 没有任何边界检查。它不会检查您是否访问了非法内存位置。
array[10]无效。使用它会调用未定义的行为。基本上任何事情都可能发生,比如崩溃、垃圾值等
标签: c data-structures stack