2011-12-19 55 views
1

我想打印出C中括號的所有有效組合。主要給出一個值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; 
} 

回答

3

你遞減/遞增變量,在這條線:

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

只調用後的功能,讓您得到StackOverflow,因爲函數每次調用相同的參數,andit電話本身遞歸地。

+0

哇,謝謝指出這一點。所以我改爲'_printValidParentheses(str,leftCount-1,rightCount,count + 1);'並且完美地工作。謝謝。 – 2011-12-19 23:04:57