#include <stdio.h>
#define MAX_STACK_SIZE 255
#define bool unsigned short int
#define true 1
#define false 0
struct stack{
int *pointer;
int count;
int *topOfStack;
int max;
int theStack[MAX_STACK_SIZE];
};
void initStruct(struct stack *stackStruct){
stackStruct->pointer = stackStruct->theStack;
stackStruct->topOfStack = stackStruct->theStack;
//this line is problematic
stackStruct->max = MAX_STACK_SIZE;
//
stackStruct->count = 0;
}
bool pushStack(struct stack *stackStruct,int inputValue){
if(stackStruct->count < stackStruct->max){
*stackStruct->pointer = inputValue;
stackStruct->pointer++;
stackStruct->count++;
return true;
}else
return false;
}
int* popstack(struct stack *stackStruct){
if(stackStruct->count >0){
stackStruct->pointer--;
stackStruct->count--;
return stackStruct->pointer;
}
return NULL;
}
int main(){
int c =1;
struct stack s[4];
for(int i=0;i<4;i++){
initStruct(&s[i]);
for(int j=0;j<3;j++){
pushStack(&s[i],c);
c++;
}
}
int *popValue;
for(int i=0;i<4;i++){
popValue = popstack(&s[i]);
while(popValue!=NULL){
printf("s[%d]=%d\n",i,*popValue);
popValue = popstack(&s[i]);
}
putchar('\n');
}
return 0;
}
此代码工作正常,输出为:
s[0]=3
s[0]=2
s[0]=1
s[1]=6
s[1]=5
s[1]=4
s[2]=9
s[2]=8
s[2]=7
s[3]=12
s[3]=11
s[3]=10
但是当我删除行 ||stackStruct->max = MAX_STACK_SIZE; ||因此使 max 的值未定义,我得到以下输出:
s[1]=6
s[1]=5
s[1]=4
s[3]=12
s[3]=11
s[3]=10
s[2] 和 s[0] 丢失。为什么只有这两个?当 max 的值未定义时,程序不应该崩溃吗?