Почему значения в моем стеке не появляются? - PullRequest
0 голосов
/ 11 февраля 2020

В этой функции я проверяю, сбалансированы ли скобки. Он печатает и показывает, что значения выталкиваются из стека, однако, когда я проверяю, является ли стек пустым или нет, он говорит, что стек заполнен и ничего не вытолкнуло. Я почти уверен, что это проблема с моими указателями, но я просто не понимаю.

int main() {
    int i;
    CharStack mine;
    IntStack stack2;
    char* str;

    initializeChar(&mine);

    while(strcmp(str = menu(), "exit") != 0) {
        for (i = 0; i <= strlen(str); i++){
            push(&mine, str[i]);
        }
        if (isBalancedParenthesis(&mine)){
            printf("Balanced\n");
        }
    }
    return 0;
}

//this function displays a menu: e - entering an infix. x - exiting the program
char * menu(){
    char opt;
    char* str = (char *)malloc(SIZE * sizeof(char));

    //menu option
    printf("----------MENU----------\ne - enter infix expression\nx - exit program\n");   //take this out before you submit
    scanf("%c", &opt);
    if (opt == 'e'){
        printf("\nEnter infix expression: ");
        scanf(" %[^\n]s", str);       //reads whitespace
        return str;
    }else
        return "exit";
}

 // pops top value off of struct and returns value
char pop(CharStack* stackPtr) {

    char retval;

    // Check the case that the stack is empty.
    if (empty(stackPtr))
        return EMPTY;

    // Retrieve the item from the top of the stack, adjust the top and return the item.
    retval = stackPtr->items[stackPtr->top];
    (stackPtr->top)--;
    return retval;
}

    //this function takes the infix expression and checks the balance of the parenthesis
//returns 1 if balanced and 0 otherwise
int isBalancedParenthesis(CharStack * stackPtr){
    printf("\n%d\n", stackPtr->top);

    int i = 0, retVal;
    char x;
    //loops through stack and calls push if char = ({[ and calls pop if char = )}]
    //and compares popped char to current char to see if they are equal
    for (i = 0; i < stackPtr->top; i++) {
        if (stackPtr->items[i] == '(' || stackPtr->items[i] == '{' || stackPtr->items[i] == '['){        //checks open paren
            push(stackPtr, stackPtr->items[i]);
        } else if(stackPtr->items[i] == ')' || stackPtr->items[i] == '}' || stackPtr->items[i] == ']') {      //checks closed paren
            if(stackPtr->items[i] == ')') {
                x = pop(stackPtr);
                printf("popped val = %c\n", x);
                if (x == '{' || x == '[')
                     return 0;
            }
        }
    }

    //returns 1 if final stack is empty
    if (empty(stackPtr)) {
        printf("\nbalanced");
         return 1;
    } else {
        for( i=0;i<stackPtr->top;i++)
            printf("%c ", stackPtr->items[i]);
        printf("  -  not bal");
        return 0;
    }
}
...