c - 如何复制堆对象以防止其被破坏?
问题描述
我在堆上分配了一个对象。该对象将从堆中销毁,但我需要保留它,最好是通过复制它并保存指向它的指针。
一个例子
#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;
推荐阅读
- swift - 如何快速更改日期格式 2021-30-06T05:00:00+07:00?
- java - Spring(引导)URL 冲突(由于包含)
- java - Netty Eventloop 在“keventWait”上被阻止
- .net-core - 使用启动配置文件运行的 Dotnet 不转发 commandLineArgs
- flutter - 如何使用 Paint() 在颤振中创建圆角矩形?
- android - 如何在 appState 更改时重新加载 react-native-webview 内容
- r - 计算 R data.table 中的值向量
- python - 如何只调用一次打印?
- flutter - 在 App 运行时处理权限组(多个权限) - Flutter
- php - WinInet上传文件PHP