我试图测试这个strncpy函数,我真的很沮丧,因为它会产生错误的结果。尝试在命令行上编译时,这是一些输出:
要成为orHo?
帮助将不胜感激。
以下是代码:
/* strncpy example */
#include <stdio.h>
#include <string.h>
char *
STRNCPY(char * dst, const char * src, size_t n)
{
if (n != 0) {
char *d = dst;
const char *s = src;
do {
if ((*d++ = *s++) == 0) {
/* NUL pad the remaining n-1 bytes */
while (--n != 0)
*d++ = 0;
break;
}
} while (--n != 0);
}
return (dst);
}
int main ()
{
char str1[]= "To be or not to be";
char str2[40];
/* partial copy (only 5 chars): */
STRNCPY ( str2, str1, 8 );
puts (str2);
return 0;
}