gpt4 book ai didi

c strncpy null 是否终止

转载 作者:行者123 更新时间:2023-12-04 09:49:20 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





strncpy documentation question

(6 个回答)


4年前关闭。




我正在阅读 this文件,它说:

char *strncpy(char *destination, const char *source, size_t num);

Copy characters from string Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

destination and source shall not overlap (see memmove for a safer alternative when overlapping).



但我对这句话感到困惑:

in this case, destination shall not be considered a null terminated C string (reading it as such would overflow)



自如果 num > strlen(source) ,它将填充 '\0'最后, '\0'实际上是字符串中的空(终止)字符,为什么不应将其视为空终止的 C 字符串?

我写了下面的代码来验证:
  char from[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
char to[1024];
for (int i = 0; i < 1024; i++) {
to[i] = 'e';
}
strncpy(to, from, 1024);
printf("from %s\n", from);

它适用于以下输出:
from hello
to hello

最佳答案

说的是strlen(source)的情况> num .它只会复制 num字符,其中没有一个是 NUL 并且不会添加 NUL。

关于c strncpy null 是否终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com