简体   繁体   English

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

[英]<String.h> is my implementation of my strncpy right?

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

Hello Stackoverflow 你好Stackoverflow

I am looking for my mistake, I know that when n > strlen(dest), it does abort on the real strncpy and I am wondering why it is wrong ? 我正在寻找我的错误,我知道当n> strlen(dest)时,它确实在实际strncpy上中止了,我想知道为什么这是错误的? Thanks for your help 谢谢你的帮助

You no need to append '\\0' continuously, if you want to rest of the memory of dest to be filled with zeros you can use calloc() while allocating memory 您无需连续追加'\\ 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM