在下面的代码中,我期待一些奇怪的行为(如无限循环),因为我没有提供空终止字符串作为strcmp()函数的输入.
#include <stdio.h>
int main()
{
char string1[20];
char string2[20] = {'H','e','l','l','o',};
strcpy(string1, "Hello");
// strcpy(string2, "Hellooo");
printf("Return Value is : %d\n", strcmp( string1, string2));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Return Value is : 0
Run Code Online (Sandbox Code Playgroud)
为什么它向我显示两个字符串相等?
我的猜测是当我初始化数组(string2)时,rest元素被填充为零.但是因为数组是本地的,所以不应该是这种情况.
如果数组或结构的初始化程序仅为数组或结构的某些部分提供数据,则将数组或结构的其余部分设置为0.情况就是如此string2.
我倾倒了string2,我得到了
72 101 108 108 111 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
剩下的string2就是0s
for (i = 0; i < 20; i++)
printf("%d ", string2[i]);
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我得到了
char string2[20];
string2[0] = 'H';
string2[1] = 'e';
string2[2] = 'l';
string2[3] = 'l';
string2[4] = 'o';
72 101 108 108 111 127 0 0 -27 5 64 0 0 0 0 0 -1 -78 -16 0 Return Value is : 127
Run Code Online (Sandbox Code Playgroud)
在定义部分初始化字符串时,字符串的其余部分用0s 填充.
但是,当你只是定义它然后为它们赋值时,它就会被垃圾值填充