【发布时间】:2018-07-28 15:09:50
【问题描述】:
目标是计算用户输入的 char* 中的所有元音。该程序还有其他功能,这是从 main 调用的。 我还包含了 stdio.h、stdbool.h 和 string.h
char* countWord;
int vowels;
printf("Type the word to count vowels:");
scanf("%s", &countWord);
vowels = vowelCount(countWord);
printf("%d", vowels);
以下是我使用的功能。我还尝试了 strlen(string) ,这也导致了崩溃。
int vowelCount(char* string){
int vowels;
int i;
int size;
printf("function entered");
for (; *string; string++){
if (string[i] == 'a'){
vowels++;
} else if(string[i] == 'e'){
vowels++;
} else if(string[i] == 'i'){
vowels++;
} else if(string[i] == 'o'){
vowels++;
} else if(string[i] == 'u'){
vowels++;
}
}
return vowels;
}
我做错了什么?我是 C 新手,但有其他语言的经验。 提前致谢。
【问题讨论】:
-
指针指向哪里?它是一个有效的地址吗?请务必在使用前初始化/分配指针。
-
我以为 char* countWord;初始化它
-
char *countWord(至少,对于自动存储持续时间的变量,在功能块中发生)定义了一个未初始化的指针。以任何方式访问其值或取消引用[访问该值然后尝试访问该地址处的内容](例如读取该地址处的内容,写入该地址)会产生未定义的行为。为未初始化的指针明确定义的唯一操作是为其赋值(例如,分配给实际地址)。