【发布时间】:2012-01-06 14:49:55
【问题描述】:
我想试试C memcpy功能。我有这个代码:
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
我想将前 11 个字母复制到目标数组。当我使用 printf 时,结果是“My favorite2”。为什么?
【问题讨论】:
-
为什么要使用
memcpy表示字符串?为什么不strncpy? -
@KerrekSB
strncpy(destination, "My favorite destination is...", 11);也不会添加 NUL 字节。 -
@rodrigo:好点。多么愚蠢。也许
strncat? -
在这种简单的情况下,仅初始化数组甚至是更好的策略。然后它会与
memcpy完美配合。