gpt4 book ai didi

c - 如何复制堆对象以防止其被破坏?

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

我在堆上分配了一个对象。该对象将从堆中销毁,但我需要保留它,最好是通过复制它并保存指向它的指针。

示例

#include <stdio.h>
#include <stdlib.h>

struct Human
{
int age;
char sex;
float height;
float weight;
};

struct Human *human;

void create_human(int age, char sex, float height, float weight)
{
struct Human *A = (struct Human *) malloc(sizeof(struct Human));
A->age = age;
A->sex = sex;
A->height = height;
A->weight = weight;

// copy A and save the pointer to the copy in the global variable

free(A);
}

int main()
{
create_human(22, 'M', 1.90, 100.0);
printf("Age: %d\tSex: %c\tHeight %.2f\tWeight %.2f\n", human->age, human->sex, human->height, human->weight);
}

这里我需要复制A指向的对象并使 human指向副本。

最佳答案

human = (struct Human *) malloc(sizeof(struct Human));
memcpy(human, A, sizeof(struct Human));

如果 Human 内部有指向其他结构的指针,这会稍微复杂一些!

编辑:StoryTeller 在评论中建议的更优雅的解决方案:

human = (struct Human *) malloc(sizeof(struct Human));
*human = *A;

关于c - 如何复制堆对象以防止其被破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52534940/

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