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

C语言用指针和函数统计元音辅音 编译通过但无输出或段错误

问题根因
  • 核心错误出在voyelle函数的遍历循环条件:你写的while(*word < n)逻辑完全不成立。*word是当前指针指向字符的ASCII码值,n是输入字符串的总长度,二者没有可比性。
    • 当输入字符串首字符的ASCII值大于字符串长度时,循环一次都不执行,就会输出0元音0辅音的结果
    • 当循环误判持续执行,越过字符串末尾的\0结束符后,会访问栈上的非法内存,触发段错误
  • 额外问题:代码中定义的i、n变量属于冗余内容,全程没有实际作用
修复方案

把循环条件替换为字符串遍历的标准判断逻辑,判断当前字符不是字符串结束符即可,修复后的完整代码如下:

#include <stdio.h>
#include <string.h>
#define SIZE 1000

void voyelle(char *word)
{
 int cons=0,vowel=0;
 // 判断当前字符不是字符串结束符就继续遍历
 while(*word != '\0')
 {
    if((*word>='a'&& *word<='z')||(*word>='A'&& *word<='Z'))
    {
        if(*word=='a'|| *word=='A'|| *word=='e'||*word=='E'||*word=='i'||*word=='I'||*word=='o'||*word=='O'||*word=='u'||*word=='U')
        {
            vowel++;
        }
        else
            cons ++;
    }
    word++;
 }
 printf("Your text count:%d vowels and %d consonnants",vowel,cons);
}
int main(void)
{
 char text[SIZE];
 printf("Input your text: ");
 fgets(text,SIZE,stdin);

 voyelle(text);

 return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:57:00