为什么二维字符数组在 C 中会有这样的行为?

问题描述 投票:0回答:1

最近我又回到了 C 语言,并认为 HackerRank 会是一个不错的开始。 有这个问题:https://www.hackerrank.com/challenges/for-loop-in-c

我试过这个:

int main() 
{
    int a, b;
    scanf("%d\n%d", &a, &b);
    char rep[9][5] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    for(int i = a; i <= b; i++)
    {
        if(i <= 9 && i >= 1)
        {
            printf("%s\n", rep[i - 1]);
        }
        else
        {
            printf((i % 2 == 0) ? "even\n" : "odd\n"); 
        }     
    }

    return 0;
}

并得到这个输出:

eightnine
nine
even
odd

我知道执行此操作的首选方法是使用 const char * 数组,但这不应该也有效吗?为什么它会多打印一个“九”?

arrays c char printf
1个回答
0
投票

像这样的字符串文字

"three"
包含6个字符,包括终止零字符
'\0'

所以你需要声明数组

rep
至少像

char rep[9][6] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

虽然这样声明会更好

const char *rep[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
© www.soinside.com 2019 - 2024. All rights reserved.