[英]Simple stack program in C
#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的值不確定時,程序是否應該崩潰?
沒什么 stackStruct->max
的值是不確定的,因此涉及該變量的任何代碼的行為以及在該變量之后運行的代碼都是不確定的。 它可能會在您的臉上丟下一塊餡餅。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.