Ada*_*ile 2 c++ string structure
我的结构如下:
typedef struct
{
std::wstring DevAgentVersion;
std::wstring SerialNumber;
} DeviceInfo;
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用它时,我会遇到各种内存分配错误.
如果我尝试将它传递给这样的函数:
GetDeviceInfo(DeviceInfo *info);
Run Code Online (Sandbox Code Playgroud)
我会得到一个运行时检查错误抱怨我在使用它之前没有初始化它,我似乎修复了:
DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo));
Run Code Online (Sandbox Code Playgroud)
但是,在函数中,当我尝试设置任何结构stings时,它会抱怨我在尝试为字符串设置值时尝试访问错误的指针.
初始化此结构的最佳方法是什么(以及它的所有内部字符串?
您应该使用new
而不是malloc
,以确保构造函数被调用DeviceInfo
及其包含的wstring
s.
DeviceInfo *info = new DeviceInfo;
Run Code Online (Sandbox Code Playgroud)
通常,最好避免malloc
在C++中使用.
此外,delete
请在使用完毕后确保指针.
编辑:当然,如果您只需要info
在本地范围内,则不应在堆上分配它.只需这样做:
DeviceInfo info; // constructed on the stack
GetDeviceInfo( &info ); // pass the address of the info
Run Code Online (Sandbox Code Playgroud)