1. 程式人生 > 其它 >C++拷貝記憶體的方式給屬性賦值

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;
}