首页 > 解决方案 > 如何复制堆对象以防止其被破坏?

问题描述

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

一个例子

#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指向副本。

标签: c

解决方案


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

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

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

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

推荐阅读