c++11结构体字符串初始化

tech2022-09-17  94

struct MyMsg { char* message; char buffer[256]; MyMsg() { memset(this, '\0', sizeof(MyMsg)); const char* msg = "你好世界"; message = new char[strlen(msg)+1]; memset(message, 0, strlen(msg)+1); memcpy(message, msg, strlen(msg)); const char* buf = "哈哈哈哈"; memset(buffer, 0, sizeof(buffer)); memcpy(buffer, buf, strlen(buf)); } }

拓展:诸如使用容器数据类型 “typedef std::list< MyMsg>* PListMsg;” 时,因为MyMsg成员变量带有指针,不管是什么类型的指针都需要申请堆空间(new)而不是以取址符(&)传递的地址赋值,否则在追加到容器后相关指针指向的数据大概率会被覆盖!

最新回复(0)