문제

#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;
}

this code is working correctly and the output is :

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

but when I delete the line ||stackStruct->max = MAX_STACK_SIZE; ||therefore making the value of max undefined I get this output:

s[1]=6
s[1]=5
s[1]=4


s[3]=12
s[3]=11
s[3]=10

s[2] and s[0] are missing. why only these two? shouldn't the program just crash when the value of max is undefined?

도움이 되었습니까?

해결책

It shouldn't anything. The value of stackStruct->max is undefined so the behaviour of any code involving that variable and the code that runs after it is undefined. It may very well throw a pie in your face.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top