【问题标题】:Print Parentheses Pair, get segmentation fault打印括号对,得到分段错误
【发布时间】:2023-03-14 01:11:01
【问题描述】:

我想打印出 C 中所有有效括号的 n-paris 组合。在主中我给出一个值 3。那是我想打印出所有有效括号的组合与 3 个左括号和 3 个右括号。但是,我遇到了分段错误,gdb 打印到_printValidParentheses(str, leftCount--, rightCount, count++); 行。我想知道有人知道我为什么会出错吗?谢谢。

void printString(char * str) {
    while (*str) {
        printf("%c", *str++);
    }
    printf("\n");
}

void _printValidParentheses(char str[], int leftCount, int rightCount, int count) {
    if (leftCount < 0 || rightCount < 0) {
        return;
    }

    if (leftCount == 0 && rightCount == 0) {
        printString(str);
        return;
    } else {
        if (leftCount > 0) {
            str[count] = '(';
            _printValidParentheses(str, leftCount--, rightCount, count++);
        } 

        if (rightCount > leftCount) {
            str[count] = ')';
            _printValidParentheses(str, leftCount, rightCount--, count++);
        }

    }
}

void printValidParentheses(int n) {
    char *str = malloc(sizeof(char) * n * 2);
    _printValidParentheses(str, n, n, 0);
}

int main() {
    printValidParentheses(3);
    return 1;
}

【问题讨论】:

    标签: c segmentation-fault parentheses


    【解决方案1】:

    你减少/增加这一行中的变量:

    _printValidParentheses(str, leftCount--, rightCount, count++);
    

    只有在你调用函数之后,所以你会得到StackOverflow,因为每次调用函数时都使用相同的参数,并且它会递归调用自身。

    【讨论】:

    • 哇,谢谢指出这一点。所以我改为_printValidParentheses(str, leftCount-1, rightCount, count+1); 并且工作得很好。谢谢。
    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多