我正在学习 C,我有疑问。在本练习中,我必须编写一个名为“双重荷兰语”的游戏,您可以在其中学习练习弦乐。我遇到的问题是程序由于 for 循环条件(在第一个 for 循环中)而停止执行。当我打印字符串的长度时,strlen() 函数在 main 和 ayInFrontOfConsonant 函数中运行良好,但我不明白为什么程序停止工作。在 Xcode 中,我收到消息:Thread 1: EXC_BAD_ACCESS。很感谢任何形式的帮助。
void ayInFrontOfConsonant(char *str)
{
char consonants[42] = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B',
'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'V', 'W', 'X', 'Y', 'Z'};
int a=(int)strlen(str);
printf("\n Length of str in ay function: %d\n",a);
int i=0,j=0;
for(i=0;i<strlen(str);i++) //problem is here
{
for(j=0;j<strlen(consonants);j++)
{
if(str[i]==consonants[j])
{
//insertChar(str, 'a', i);
}
}
}
}
int main()
{
int a=0;
printf("** Welcome to the Double Dutch game **\n");
char myString[36];
printf("Please enter a string: ");
scanf("%[^\n]s", myString);
a=strlen(myString);
printf("Length of string in main: %d\n",a);
ayInFrontOfConsonant(myString);
printf("Double dutch traslation: %s\n",myString);
return 0;
}
最佳答案
您的数组没有 null
终止符。
取而代之的是,使用 sizeof consonants/sizeof *consonants
— 或者在这种特殊情况下,因为 sizeof *consonants
肯定是 1
,那么只是辅音的大小
。
不应在 for
循环的条件下使用 strlen()
,因为它每次都会遍历字符串,直到找到 null
您的代码中缺少终止符
char consonants[42] = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B',
'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'V', 'W', 'X', 'Y', 'Z'};
如果你使用
const char *consonant = "bcdf ...";
相反,编译器会添加'\0'
终止符,您也可以显式添加它
char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B',
'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'V', 'W', 'X', 'Y', 'Z', '\0'};
一个c程序员可能会这样写,
#include <stdlib.h>
void ayInFrontOfConsonant(char *str)
{
char consonants[] = {
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B',
'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'
};
for (size_t i = 0; str[i] != '\0'; i++) {
for (size_t j = 0; j < sizeof consonants; ++j) {
if (str[i] == consonants[j]) {
// Do here whatever you wanted to do
}
}
}
}
但事实并非如此,因为不需要扫描整个辅音数组,因为它们可以排序,并且您可以使用二分搜索,这将大大改进算法。
关于c - 为什么 strlen 函数在此 for 循环条件下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888375/