c - 为什么这个 'strncpy' 的实现有效?

标签 c string strcpy strlcpy

我必须重写一个模仿 strncpy 行为的函数,经过多次试验和错误,一些外部帮助,这是最终代码:

 15 char    *ft_strncpy(char *dest, char *src, unsigned int n)
 16 {
 17     unsigned int i;
 18     unsigned int size;
 19
 20     i = 0;
 21     size = 0;
 22     while (src[i] && i < n)
 23     {
 24         dest[i] = src[i];
 25         i++;
 26     }
 27     while (i < n)
 28     {
 29         dest[i] = '\0';
 30         i++;
 31     }
 32     return (dest);
 33 }

它完美地工作,但我不明白这部分:

 while (i < n)
 {
     dest[i] = '\0';
     i++;
 }

此时,i 的值应该是 (n - 1) 对吧?所以 '\0' 进入 dest[n-1] 并且循环结束,因为 i 变得等于 n 然后函数结束。

我们剩下一个看起来像这样的字符串:

"string copied\0not copied part"

并打印成:string copiednot copyed part

我的问题是:

  • 为什么 dest[n-1]='\0'dest[n]='\0' 而不是那个 while 循环,返回string copied 而不是 'string copiednot copied part' 当他们基本上做同样的事情时?

  • 当我使用 dest[n-1] = '\0' 而不是?

这是我用来运行测试并尝试理解的主要/替代函数:

int main()
{
     char str[] = "test de chaine";
     char *str2 = "chaine de test";

     ft_strncpy(str, str2, 6);
     printf("%s", str);
     return 0;
}

char    *ft_strncpy(char *dest, char *src, unsigned int n)
 {
     unsigned int i;
     unsigned int size;

     i = 0;
     size = 0;
     while (src[i] && i < n)
     {
         dest[i] = src[i];
         i++;
     }
         dest[n-1] = '\0';
     return (dest);
 }

最佳答案

the value of i should be (n - 1) right ?

情况不一定如此,因为第一个 while循环在遇到 \0 时退出字符(即使 i 小于 n-1 )。

while -loop 用于确保 dest 的剩余部分数组已正确初始化为 \0 .

您看到的“错误”行为(打印的字符串超出复制字符串的末尾)是由于两个循环以相同条件退出:第一个循环在 i 时退出。变成 n因为第二个循环有检查 i<n , 它不运行。

这对应于手册中描述的行为:

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

如果你要复制一个字符串 str值为 abc , 它会在下面的示例中正确显示它:

#include <stdio.h>

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int i;
    unsigned int size;

    i = 0;
    size = 0;
    while (src[i] && i < n)
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

int main()
{
     char str[] = "test de chaine";
     char *str2 = "abc";

     ft_strncpy(str, str2, 6);
     printf("%s\n", str);
     return 0;
}

关于c - 为什么这个 'strncpy' 的实现有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54770801/

相关文章:

c - C 中的 strcpy 段错误

c - 程序打印 Windows 路径?

c - 为什么这些构造使用增量前和增量后未定义的行为?

在C中的递归函数中连接字符

regex - 如何找到字符串中元素的分隔符?

Ruby:将用户输入与字符串进行比较

c++ - 我的 strcpy 有什么问题?

c - __int32 是否已定义?

c - mmap,memcpy 将文件从 A 复制到 B

string - Prolog:检查字符串的第一个和最后一个字符是否是左右花括号 ('{' & '}' )