struct和malloc記憶體互轉例子

BangZeng發表於2024-05-17
#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();
}

程式碼如上:

輸出結果

相關文章