关于 strncpy
的以下内容:http://www.cplusplus.com/reference/clibrary/cstring/strncpy/ ,它提到了以下内容:
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
这句话是什么意思?
最佳答案
这意味着,例如,如果您的源字符串是 20 个字符加上一个空终止符,而您的 strncpy
指定少于 21 个字符,则目标字符串将不会附加一个空值。
这是因为它的工作方式:strncpy
保证它将恰好写入 N 个字节,其中 N 是传入的长度值。
如果源字符串的长度(无空字节)小于该长度,它将用空值填充目标区域。如果它等于或大于,您将不会向目标添加空值。
这意味着它在技术上可能不是您获得的 C 字符串。这可以用如下代码解决:
char d[11]; // Have enough room for string and null.
strncpy (d, s, 10); // Copy up to 10 bytes of string, null the rest.
d[10] = '\0'; // Then append null manually in case s was too long.
您分配 11 个字节(数组索引 0..10),最多复制 10 个(索引 0..9),然后将第 11 个(索引 10)设置为空。
下图显示了使用 strncpy (d, s, 10)
将各种大小的字符串写入 10 个字符的区域的三种可能性,其中 .
表示空值字节:
s d
------------- ----------
Hello. Hello.....
Hello Fred. Hello Fred
Hello George. Hello Geor
请注意,在第二种和第三种情况下,没有写入空字节,因此,如果您将 d
视为字符串,您可能会对结果感到失望。
关于c++ - strncpy 文档问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4768271/