c - strncpy 引入有趣的角色

标签 c strncpy

当我在我的机器上运行一些代码时,它会按照我的预期运行。

当我在同事身上运行它时,它表现不佳。这就是发生的事情。

我有一个字符串,其值为:

croc_data_0001.idx

当我对长度为 18 的字符串执行 strncpy 时,我复制的字符串的值为:

croc_data_0001.idx♂

如果我执行以下操作

myCopiedString[18]='\0';
puts (myCopiedString);

那么复制的字符串的值为:

croc_data_0001.idx

是什么导致了这个问题?为什么通过将最后一个字符设置为 \0 可以解决这个问题?

最佳答案

根据 http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

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 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.

因此,您需要使用“\0”手动终止您的目的地。

关于c - strncpy 引入有趣的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464780/

相关文章:

arrays - 将 volatile 数组传递给 strncpy

c - 给指针char赋值?

c - 建立二叉树的替代方法?

C linux shmget 参数无效

c - 如何从字符串中删除重复项

C: 创建自己的 strncpy 版本

c - 读取 2 个 fgets 输入以使用 strncpy 作为名字和姓氏

c - 如何从 char[][] 写入文件?

c++ - c_str() ing 字符串 - 除了第一行之外的所有其他行都将丢失

c - strncpy 并不总是空终止