【发布时间】:2020-04-16 12:52:46
【问题描述】:
我试图思考如何制作函数strncpy,我遇到了这个问题。
char src[] = "123456789A";
char dest[10];
int n = 10;
printf("strncpy:%s\n", strncpy(dest, src, n));
输出
strncpy:123456789A123456789A
发生了什么?
【问题讨论】:
-
dest没有空间用于终止空字符,因此最终不会有空间,因此 printf 将继续从内存中打印,直到找不到空字符为止。 -
遇到未定义的行为
-
仔细阅读
strncpy的文档,特别是当字符串大于指定的最大大小时会发生什么。基本上strncpy函数是没用的。使用strncpy有意义的用例并不多。
标签: c buffer c-strings strncpy