我正在学习c中的字符串.我使用code :: blocks作为编译器,即使它不仅仅用于c.因此,下面代码的问题是string2的输出是存储的5个字符加上string1的输出.我会给你看:
#include <stdio.h>
#include <string.h> /* make strncpy() available */
int main()
{
char string1[]= "To be or not to be?";
char string2[6];
/* copy first 5 characters in string1 to string2 */
strncpy (string2, string1, 5);
printf("1st string: %s\n", string1);
printf("2nd string: %s\n", string2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
1st string contains: To be or not to be?
2nd string contains: To be To be or not to be?
Run Code Online (Sandbox Code Playgroud)
如果你问我,那超过5个字符......
Vin*_*ura 10
从strncpy
手册页:
没有空字符隐式附加到目标的末尾,因此如果源中的C字符串的长度小于num,则目标将仅以空值终止.
由于原始字符串的长度大于5,因此不添加NULL.
正如其他人所指出的那样,为它增加一些安全性:
strncpy (string2, string1, sizeof(string2));
string2[sizeof(string2)-1] = '\0';
Run Code Online (Sandbox Code Playgroud)
请注意,如果string2
是通过以下方式获得malloc()
:
char * string2 = malloc(123); //sizeof(string2) == sizeof(void *) and not 123
Run Code Online (Sandbox Code Playgroud)
上面的代码会失败.
为了完整起见,这里是代码:http://ideone.com/eP4vd