这个代码不能正常输出是因为在Count_String函数中没有返回值,而在主函数中也没有对返回值进行处理。应该将Count_String函数的返回值类型改为int,并在函数末尾添加return count;语句,同时在主函数中添加printf('%d', Count_String(a,b));语句来输出结果。

另外,建议使用fgets代替gets函数,以避免缓冲区溢出的问题。

以下是优化后的代码:

#include <stdio.h>

int Count_String(char a[], char b[]) {
    char *p1, *p2;
    int count = 0;
    fgets(a, 32, stdin);
    fgets(b, 32, stdin);
    a[strcspn(a, "\n")] = 0; // 去除fgets读取的换行符
    b[strcspn(b, "\n")] = 0; // 去除fgets读取的换行符
    p1 = a;
    p2 = b;
    while (*p1 == *p2) {
        if (*p1 == *p2) {
            while (*p1 == *p2 && *p2 != '\0') {
                p1++;
                p2++;
            }
        } else
            p1++;
        if (*p2 == '\0') {
            count++;
            p2 = b;
        }
    }
    return count;
}

int main() {
    char a[32];
    char b[32];
    printf('%d', Count_String(a, b));
    return 0;
}
C语言代码分析:字符串计数程序错误及优化

原文地址: https://www.cveoy.top/t/topic/nqIV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录