C++拷贝内存的方式给属性赋值

#include <iostream>
#include <string.h>


using namespace std;

struct TestStruct {
    int id;
    char *a{nullptr};
    char *b{nullptr};
    char *c{nullptr};
};
int main(int argc, const char *argv[]) {
    int size = sizeof(TestStruct) + 6 + 3 + 2;
   auto st = (TestStruct *) malloc(size);
    st->id = 100;

    char *c = "qiumc";
    char *d = reinterpret_cast<char *>(st + sizeof(TestStruct));
    memcpy_s(d, 6, c, 6);
    st->a = d;

    c = "11";
    d = reinterpret_cast<char *>(st + sizeof(TestStruct) + 6);
    memcpy_s(d, 3, c, 3);
    st->b = d;

    c = "x";
    d = reinterpret_cast<char *>(st + sizeof(TestStruct) + 6 + 3);
    memcpy_s(d, 2, c, 2);
    st->c= d;

    cout << st->a << endl;
    cout << st->b << endl;
    cout << st->c << endl;
}

 

上一篇:2021-10-17


下一篇:64位Linux系统下32位程序与64位程序数据类型分析