gpt4 book ai didi

C编程: strlcpy with len = 0

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:05 25 4
gpt4 key购买 nike

<分区>

我只是在学习使用 C 语言进行编程。今天,我正在尝试编写自己的 strlcpy 函数,但遇到了问题。

为了测试我的函数,我将结果与“官方”函数的结果进行比较。一切正常,除了...当我将 0 作为 len arg 时。strcpy 函数似乎在目标字符串中放置了一个垃圾字符,我真的不明白为什么。

这是函数的原型(prototype): size_t strlcpy(char * restrict dst, const char * restrict src, size_t dstsize);

感谢您的帮助!

好的。我想做很多测试,这就是我在循环内调用函数的原因。

这是我的主要功能的一部分,测试功能:

do
{
/* Ask for first string */
printf("\nGive me a string (0 to stop): ");
gets(str);

/* Ask for a number */
printf("Now, give me a number please: ");
scanf("%d", &i);
while (getchar() != '\n');

/* I test with the "official function */
j = strlcpy(str2, str, i);
printf("Here is the expected result: %s\n", str2);
printf("Num returned: %d\n", j);

/* Now I test using my function */
j = ft_strlcpy(str3, str, i);
printf("Here is my result: %s\n", str3);
printf("Num returned: %d\n", j);

}while (str[0] != '0');

这是我编写的函数:

unsigned int    ft_strlcpy(char *dest, char *src, unsigned int size)
{
unsigned int cpt;
unsigned int i;

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

在函数中我不应该调用标准库中的任何函数。我的主要只是在这里进行测试。函数原型(prototype)是我老师给的,这就是我不尊重原作的原因。

抱歉,我需要将我的代码放在这里,感谢您的帮助。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com