struct和malloc内存互转例子
#include <iostream> typedef struct DS1001 { unsigned int a; unsigned char b; unsigned int c; unsigned char d; unsigned short e; } DS1001; void TestMallocToStruct() { int nsize = sizeof(DS1001); unsigned char* mallocdata = (unsigned char*)malloc(sizeof(unsigned char) * nsize); memset(mallocdata, 0, sizeof(unsigned char) * nsize); unsigned char* _8bit = (unsigned char*)malloc(sizeof(unsigned char)); //a *_8bit = 1; memcpy(mallocdata + 0, _8bit, sizeof(unsigned char)); *_8bit = 0; memcpy(mallocdata + 1, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 2, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 3, _8bit, sizeof(unsigned char)); //b *_8bit = 2; memcpy(mallocdata + 4, _8bit, sizeof(unsigned char)); *_8bit = 0; memcpy(mallocdata + 5, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 6, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 7, _8bit, sizeof(unsigned char)); //c *_8bit = 3; memcpy(mallocdata + 8, _8bit, sizeof(unsigned char)); *_8bit = 0; memcpy(mallocdata + 9, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 10, _8bit, sizeof(unsigned char)); memcpy(mallocdata + 11, _8bit, sizeof(unsigned char)); //d *_8bit = 4; memcpy(mallocdata + 12, _8bit, sizeof(unsigned char)); *_8bit = 0; memcpy(mallocdata + 13, _8bit, sizeof(unsigned char)); //e *_8bit = 5; memcpy(mallocdata + 14, _8bit, sizeof(unsigned char)); *_8bit = 0; memcpy(mallocdata + 15, _8bit, sizeof(unsigned char)); //强转成DS1001进行数据打印 DS1001* convertdata = (DS1001*)mallocdata; printf("a:%d\n", convertdata->a); printf("b:%d\n", convertdata->b); printf("c:%d\n", convertdata->c); printf("d:%d\n", convertdata->d); printf("e:%d\n", convertdata->e); } //拷贝内存后用结构体输出值 void StructToMallocValue() { unsigned char* mallocdata = (unsigned char*)malloc(sizeof(DS1001)); memset(mallocdata, 0, sizeof(DS1001)); printf("DS1001:%d\n", sizeof(DS1001)); unsigned int* e = (unsigned int*)malloc(sizeof(unsigned int)); *e = 1; DS1001 ds1001 = { 1,2,3,4,5 }; // printf("&ds1001.a:%x\n",&ds1001.a); // printf("&ds1001:%x\n",&ds1001); memcpy(mallocdata, (unsigned char*)&ds1001, sizeof(DS1001)); int nsize = sizeof(ds1001); for (int j = 0; j < nsize; j++) { printf("mallocdata:%d\n", *(mallocdata + j)); } free(mallocdata); } int main() { TestMallocToStruct(); StructToMallocValue(); }
代码如上:
输出结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具