Skip to content

关于调用函数时临时变量

约 197 字小于 1 分钟

2024-11-03

......
	result = match(str, ch1, ch2);

    puts(result);
}

char *match(char *s, char ch1, char ch2) {
    char temp[50];

    //筛选ch1和ch2之间的字符
    while (*s != '\0') {
        if (*s == ch1) {
            for (int i = 0; *s != ch2; i++) {
                temp[i] = *s;
                s++;
            }
            break;
        }
        s++;
    }
    return temp;//此时想要返回筛选过的字符串的地址
}

结果

​ 无法输出任何值

原因

​ temp属于非主函数内,当match()函数结束后即被销毁

解决方法

......
	result = match(str, ch1, ch2);

    puts(result);
}

char *match(char *s, char ch1, char ch2) {
    char static temp[50];//将temp定义为静态变量,不会随函数失效而销毁

    //筛选ch1和ch2之间的字符
    while (*s != '\0') {
        if (*s == ch1) {
            for (int i = 0; ; i++) {
                temp[i] = *s;
                if (*s == ch2) {
                    break;
                }
                s++;
            }
            break;
        }
        s++;
    }
    return temp;
}
贡献者: edge-sky