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

字母统计函数出现Segmentation fault问题求助

C语言程序Segmentation Fault问题排查与修复

错误点分析

  • 函数调用语法错误:传递数组参数时直接写数组名即可,无需加[]。原代码中vcount(x[])、uccount(x[])、lccount(x[])属于非法写法,会导致编译异常,进而引发运行时错误。
  • 数组越界访问:
    • lccount和uccount函数中,循环条件i<=10错误:数组x长度为10,有效索引范围是0-9,i=10会访问超出数组边界的内存,触发未定义行为,需改为i<10。
    • lccount中j<=26错误:lowalphabet包含26个小写字母,有效索引0-25,j=26会越界访问,需改为j<26;同理uccount中的j<=26也要改为j<26。
    • vcount函数中,i<=20完全超出x的长度范围,改为i<10;j<=10错误:vowels有10个元素,有效索引0-9,改为j<10。
  • printf格式错误:原代码直接换行不符合C语法规则,需用\n表示换行;%dlowercase缺少空格,应改为%d lowercase。
  • 主函数不规范:C标准中void main并非标准写法,建议使用int main()并在函数末尾添加return 0;。

修正后的代码

#include <stdio.h>

int lccount(char x[10]){
    int count=0,i,j;
    char lowalphabet[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for(i=0;i<10;i++){
        for(j=0;j<26;j++){
            if(x[i]==lowalphabet[j]){
                count++;
            }
        }
    }
    return count;
}

int uccount(char x[10]){
    int count=0,i,j;
    char upalphabet[]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    for(i=0;i<10;i++){
        for(j=0;j<26;j++){
            if(x[i]==upalphabet[j]){
                count++;
            }
        }
    }
    return count;
}

int vcount(char x[10]){
    int count=0,i,j;
    char vowels[]={'a','e','i','o','u','A','E','I','O','U'};
    for(i=0;i<10;i++){
        for(j=0;j<10;j++){
            if(x[i]==vowels[j]){
                count++;
            }
        }
    }
    return count;
}

int main(){
    char x[10]={'a','W','E','R','s','d','a','e','i','A'};
    int v,uc,lc;
    v=vcount(x);
    uc=uccount(x);
    lc=lccount(x);
    printf("%d vowels\n%d uppercase\n%d lowercase",v,uc,lc);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:01:32