char *strncpy(char *dest, char *src, unsigned int n)
{
unsigned int a;
a = 0;
while (src[a] && a < n)
{
dest[a] = src[a];
a++;
}
while (a < n)//if src not bigger than n should I put '\0' at the end of dest ?
{
dest[a] = '\0';
a++;
}
dest[a] = '\0';
return (dest);
}
你好Stackoverflow
我正在寻找错误,我知道当n> strlen(dest)时,它确实在实际strncpy上中止,我想知道为什么会出错吗? 谢谢您的帮助
答案 0 :(得分:0)
您无需连续追加'\ 0',如果您想将dest
的剩余内存填充为零,则可以在分配内存时使用calloc()
char *strnncpy(char *dest, char *src, unsigned int n)
{
unsigned int a;
a = 0;
while ( src[a] && a < n)
{
dest[a] = src[a];
a++;
}
dest[a] = '\0';
return (dest);
}