0
#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 的值未定义时,程序不应该崩溃吗?

4

1 回答 1

1

应该没什么。的值stackStruct->max是未定义的,因此涉及该变量的任何代码的行为以及在它之后运行的代码都是未定义的。它很可能会在你的脸上扔馅饼。

于 2013-10-09T20:47:35.513 回答