gpt4 book ai didi

c - 自己版本的 strncpy 不应该工作,但它确实有效

转载 作者:行者123 更新时间:2023-11-30 17:48:33 25 4
gpt4 key购买 nike

这是代码。

#include <stdio.h>
#define MAXOUTPUT 10

void copy_n(char des[], char src[], int n);

int main(void)
{
int i;
char output[MAXOUTPUT];
copy_n(output, "SomeTestInputHere", 26);

printf("%s\n", output);
for(i=0;output[i]!='\0';i++)
printf("%c\n", output[i]);

return 0;
}

void copy_n(char des[], char src[], int n)
{
int i;

for(i=0;i<MAXOUTPUT;i++)
{
if(i<n)
des[i]=src[i];
else
des[i]='\0';
}
}

为什么在逐个字符打印字符串或字符时不会压碎?终止 NUL 从哪里来?它用于 C 上的 Reek 指针,应该复制 n 个字符,当 des>=src 时用 NUL 填充。但是当 src>des 时它应该复制所有字符而不终止 NUL。

最佳答案

您的 copy_n 函数 for 循环使用常量 MAXOUTPUT 作为循环中的保护;并且 MAXOUTPUT 的值为 10。

关于c - 自己版本的 strncpy 不应该工作,但它确实有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547590/

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