gpt4 book ai didi

c - 需要帮助来使用 memcpy 处理缓冲区

转载 作者:行者123 更新时间:2023-11-30 19:55:41 24 4
gpt4 key购买 nike

在下面的代码中,当我使用fwrite时,它给出了正确的o/p。虽然 memcpy 不起作用。

typedef struct
{
char *p1;
char *p2;
} node;
char s[] = "hello";
char t[] =" there";
node t1, t2;
char str;
FILE op_f;

t1.p1 = malloc(sizeof(strlen(s));
t1.p2 = malloc(sizeof(strlen(s));

t2.p1 = malloc(sizeof(strlen(s));
t2.p2 = malloc(sizeof(strlen(s));

t1.p1 = s;
t1.p2 = t;
copy(&t1,&t2);

str = malloc(sizeof(strlen(s) + strlen(t));
/* gives o/p hello there */
fwrite(t2.p1,1,strlen(s),op_f);
fwrite(t2.p1,2,strlen(s),op_f);

/* gives o/p there */
memcpy(str,t2.p1,strlen(s));
memcpy(str,t2.p2,strlen(s));

有没有办法将缓冲区复制到str?

PS:以上代码仅供引用,并非实际代码

最佳答案

您应该将 str 声明为 char 数组,而不是单个字符:

char str[500];

当 str 被声明为数组时,str 是一个指针(指向数组的第一个元素)。在你的代码中 - str 是一个字符,但不是指针。 Memcpy 需要指针作为第一个和第二个参数

此外,对没有 sizeof 的字符串使用 malloc:

 t1.p2 = malloc(strlen(s)+1);

此外,fwrite 的使用不正确,因为 op_f 未使用 fopen 初始化,如下所示:

 op_f = fopen("filename.txt", "w");

关于c - 需要帮助来使用 memcpy 处理缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6758108/

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