You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复C语言字符串字符统计代码计数不重置的问题?

问题原因

你的代码存在两处核心错误导致运行结果不符合预期:

  • count 变量未初始化,且每次循环统计前没有重置为0,第一次的统计值会累加到后续的查询结果中
  • 指针ptr仅在进入循环前赋值一次为字符串首地址,第一次统计完后ptr已经移动到字符串末尾\0的位置,后续循环统计时都是从字符串末尾之后的非法内存遍历,自然匹配不到任何字符,所以即使重置了count结果也始终为0

另外还有两处不规范写法:

  • ptr = &word 写法错误,word本身就是数组首地址,直接赋值ptr = word即可
  • void main 不是C标准的主函数写法,且scanf("%[^\n]")存在缓冲区溢出风险

修复方案

每次查询统计前,同时重置count为0、将ptr重新指向字符串首地址,同时修正不规范写法即可,修复后的完整代码如下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char word[100],*ptr,input;
    int count,i;
    printf("Enter the word : ");
    // 限制输入长度避免溢出,数组长度100留1位存结束符
    scanf("%99[^\n]", word);
    do
    {
        printf("Enter the letter : ");
        scanf(" %c", &input);
        if(input == '-'){
                printf("Exit.");
                return 0;
        }
        // 每次统计前重置count和ptr
        count = 0;
        ptr = word;
        for(i=0;word[i] != '\0';i++)
        {
            if(*ptr == input)
                count++;
            ptr++;
        }
        printf("Has %d of '%c'",count,input);
        printf("\n");
    }while(input != '-');
    return 0;
}

内容的提问来源于stack exchange,提问作者KillingSpree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:30:00