代码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) 为什么外部添加NULL '\0'
在 strncpy()
中是必需的但不在strncat()
如图code 3
和 code 4
分别?
注意- 如果在 code 4
中我做char str[100];
然后@#^hello
已显示,但字符串仍未添加 NULL 结束
最佳答案
代码1
char str[]="abc";
char str1[]="hello computer";
strcat(str,str1);
这会溢出 str
。该行为是未定义的,可以假设任何输出(实际上,str1
可能正在被自身覆盖,这就是为什么您看到 abshello computer
作为输出)。
代码2
char str[100]; //notice the change from code 1
char str1[]="hello computer";
strcat(str,str1);
您在 hello computer
之前看到垃圾,因为 str
未初始化。碰巧它在第一个 NUL 之前的测试时包含 "@#^"
。
代码3
char str[100];
char str1[]="hello computer";
strncpy(str,str1,5);
str[5]='\0'; //external addition of NULL
这是正确的。 strncpy
复制 "hello computer"
的前五个字符并且不以 NUL 结尾。你应该自己做(就像你所做的那样)。如需进一步引用,请参阅 strcpy
的手册页:
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
代码4
char str[100]="abc";
char str1[]="hello computer";
strncat(str,str1,5);
strncpy
和strncat
之间的一个区别是strncat
NUL 终止结果字符串。来自 strncat
的手册页:
As with strcat(), the resulting string in dest is always null-terminated.
关于c - 关于 strcat()、strncpy()、strncat() 等字符串函数的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21290075/