【发布时间】:2014-01-22 17:41:55
【问题描述】:
代码 1
int main()
{
char str[]="abc";
char str1[]="hello computer";
strcat(str,str1);
printf("the concatenated string is : %s\n",str);
return 0;
}
输出-abchello computer
代码 2
int main()
{
char str[100]; //notice the change from code 1
char str1[]="hello computer";
strcat(str,str1);
printf("the concatenated string is : %s\n",str);
return 0;
}
输出-@#^hello computer
代码 3
int main()
{
char str[100];
char str1[]="hello computer";
strncpy(str,str1,5);
str[5]='\0'; //external addition of NULL
printf("the copied string is : %s\n",str);
return 0;
}
输出-hello
代码 4
int main()
{
char str[100]="abc";
char str1[]="hello computer";
strncat(str,str1,5);
printf("the concatenated string is : %s\n",str);
return 0;
}
输出-abchello
问题
Q-1) 为什么abchello computer 显示在code 1 和@#^hello computer 在code 2 中?垃圾@#^从哪里来?
Q-2) 为什么strncpy() 需要外部添加NULL '\0' 而strncat() 不需要,如code 3 和code 4 所示?
注意 - 如果在 code 4 我做 char str[100]; 然后 @#^hello 显示,但字符串仍然结束而不添加 NULL
【问题讨论】:
-
'\0'是NUL并且不同于NULL。 -
C 标准也不要求编译器生成初始化
auto变量的代码,而不是0或其他任何东西。
标签: c string output strcat strncpy