gpt4 book ai didi

Why this code prints contents of an irrelevant char array?(为什么这段代码打印不相关字符数组的内容?)

转载 作者:bug小助手 更新时间:2023-10-24 23:44:20 32 4
gpt4 key购买 nike



I was working on exercises in K&R's The C Programming Language Book. In the Exercise 2-4, I was writing an experimental code:

我当时正在做K&R的《C编程语言手册》中的练习。在练习2-4中,我编写了一个实验性代码:


void printstr(char s[])
{
int i=0;
while(s[i] != '\0')
{
printf("%c", s[i++]);
}
printf("\n");
}

int main()
{
char sa[] = {'a', 'b', 'a', 'b', 'c', 'e', 'd'};
char sb[] = {'a'};
// squeeze(sa, sb);
printstr(sb);
return 0;
}

You would expect this code prints a single "a" and then quits, right? However the output is:

您希望这段代码打印一个“a”,然后退出,对吗?但是,输出为:


$ gcc exercise_2-4.c
$ ./a.out
aababced

But if I disable definition of "sa" array by commenting it out, prints as it's expected:

但是,如果我通过注释掉“sa”数组来禁用它的定义,则会按预期打印:


gcc exercise_2-4.c
./a.out
a

I'm somehow aware of this is not happening insanely, it's tied to a reason but I really wondered about it.

不知何故,我意识到这并不是疯狂的发生,这是有原因的,但我真的很想知道。


更多回答

Where do you think the '\0' character is in the array you've passed to the function? char sb[] = "a"; would add one at the end, but if you construct the array with character literals it will not. You'd need to add it yourself.

您认为‘\0’字符在您传递给函数的数组中的什么位置?Char sb[]=“a”;将在末尾添加1,但如果使用字符文字构造数组,则不会。你需要自己添加。

You need either char sb[] = {'a', '\0'}; or char sb[] = "a"; and similar for sa.

您需要char sb[]={‘a’,‘\0’};或者char sb[]=“a”;对于sa,也需要类似的内容。

Somehow I always thought it's added by automatically to end of char arrays, now I figured out. Thanks! @RetiredNinja

不知何故,我一直以为它会被自动添加到字符数组的末尾,现在我想通了。谢谢!@RetiredNinja

Because there is no terminator. Eventually it will probably find one by accident. Incorrect code behaves mysteriously, and questioning it leads you nowhere.

因为没有终结者。最终,它可能会意外地找到一个。不正确的代码行为神秘,质疑它不会给你带来任何好处。

"Anything" does not mean "random behaviour". It just means "anything", which might alsways be the same thing, always a diffenent thing, even always correct.

“任何事”并不意味着“随意的行为”。它的意思是“任何东西”,可能永远是一样的东西,永远是不同的东西,甚至永远是正确的。

优秀答案推荐

As you access arrays outside bounds, you invoke undefined behaviour (UB). Your program behaviour cannot be determined from the C language point of view.

当您访问边界外的数组时,您会调用未定义行为(UB)。您的程序行为不能从C语言的角度来确定。


You need to null terminate it yourself:

您需要自己将其设为空并终止:


   char sa[] = {'a', 'b', 'a', 'b', 'c', 'e', 'd', 0};
char sb[] = {'a', 0};

or initialize using string literals

或使用字符串文字进行初始化


   char sa[] = "ababced";
char sb[] = "a";

更多回答

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com