<string.h>是我对strncpy的实现吗?

时间:2018-08-31 09:37:17

标签: c string strncpy

  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上中止,我想知道为什么会出错吗? 谢谢您的帮助

1 个答案:

答案 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);
}