删除C中括号内的字符

5 c arrays string pointers

我制作了一个删除括号内字符的程序.输入的文本应具有匹配的开括号和右括号.

情况1:

输入:     (Hello) World
输出:World

案例2:

输入:     (Hello World
输出:(Hello World

案例3:

输入:     Hello)(World
输出:Hello)(World

案例4:

输入:     Hello((hi) World)
输出:Hello

案例5:

输入:     (Hello) hi (World)
输出:hi

这是我的代码:

#include <stdio.h>
int main(){
    char string[100] = {0};
    char removedletters[100] = {0};
    fgets(string, 100, stdin);
    char *p;
    int x = 0;
    int b = 0;
    for (p=string; *p!=0; p++) {
        if (*(p-1) == '(' && x) {
            x = 0;
        }
        if (*p == ')') {
            x = 1;
        }
        if (!x){
            removedletters[b] = *p;
            b++;
        }
    }
    puts(removedletters);
}
Run Code Online (Sandbox Code Playgroud)

案例1,3和5是正确的,但在案例2和案例4中没有.我的代码有什么问题?

Seb*_*ach 2

您正在调用未定义的行为:

for(p=string; *p!=0; p++){
    if(*(p-1) == '(' && x){
        x = 0;
    }
Run Code Online (Sandbox Code Playgroud)

第一次p++评估是在循环块的末尾,因此,第一次*(p-1)指向 的左边string,即您正在执行*(string-1)

不幸的是,如果您有未定义的行为,您将失去任何保证。