当我在我的机器上运行一些代码时,它会按照我的预期运行。
当我在同事身上运行它时,它表现不佳。这就是发生的事情。
我有一个字符串,其值为:
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/