简体   繁体   English

为什么strlen函数在这种for循环条件下不起作用?

[英]Why does strlen function not work in this for loop condition?

I am learning C and I have question. 我正在学习C并且有疑问。 In this exercise I have to program a game called double dutch where you learn to practice with strings. 在本练习中,我必须编写一个名为double dutch的游戏,在该游戏中您将学习如何练习弦乐。 The problem I ran into is that the program stops executing because of the for loop condition (in the first for loop). 我遇到的问题是,由于for循环条件(在第一个for循环中),程序停止执行。 The strlen() function works well in main and in the ayInFrontOfConsonant function at first when I print the length of the string but I don't get why the program stops working. 当我打印字符串的长度时,strlen()函数首先在main和ayInFrontOfConsonant函数中运行良好,但我不知道为什么程序会停止工作。 In Xcode I get the message: Thread 1: EXC_BAD_ACCESS. 在Xcode中,我收到消息:线程1:EXC_BAD_ACCESS。 Any help is very much appreciated. 很感谢任何形式的帮助。

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;

} }

Your array has no null terminator. 您的数组没有null终止符。

Instead of that, use sizeof consonants / sizeof *consonants — or in this particular case since sizeof *consonants is surely 1 , then just sizeof consonants . 取而代之的是,使用sizeof consonants / sizeof *consonants -或在此特定情况下,因为sizeof *consonants肯定为1 ,则仅使用sizeof consonants

You should not use strlen() in the condition of a for loop, because it traverses the string every time, until it finds the null terminator which is missing in your 您不应该在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'};

If you use 如果您使用

const char *consonant = "bcdf ...";

instead, the compiler will add the '\\0' terminator, you can also add it explicitly 相反,编译器将添加'\\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'};

A programmer would probably write this instead, 程序员可能会改写这个,

#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
            }
        }
    }
}

But not really, because there is no need to scan the whole array of consonants since they can be sorted and you can use binary search which would improve the algorithm a lot. 但这不是真的,因为不需要扫描整个辅音数组,因为可以对它们进行排序,并且可以使用二进制搜索来改善算法。

When you write a statement like char consonants [42] = { ... } , one of three things happen: 当您编写类似char consonants [42] = { ... }的语句时,会发生以下三种情况之一:

If you have 43 or more characters, the compiler gives you an error. 如果您有43个或更多字符,编译器会给您一个错误。

If you have 41 or less characters, the compiler fills the rest of the array with zeroes, and strlen() will work because there is a nul byte after the characters. 如果您有41个或更少的字符,则编译器将用零填充数组的其余部分,并且strlen()将起作用,因为字符后面有一个nul字节。

If you have exactly 42 characters, the compiler fills the array exactly to the end. 如果您恰好有42个字符,则编译器将数组完全填充到末尾。 There is no trailing zero byte. 没有尾随零字节。 strlen will not work. strlen将不起作用。

In reality, there was no reason for you to count the characters. 实际上,您没有理由要数字符。

char consonants [] = "bcdfgh..." 

would do exactly what you want. 会完全按照您想要的去做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM