当我尝试将字符串值分配给结构成员时,我的程序崩溃了。 我怀疑结构中的成员(字符串类型)从未在内存中正确分配。
这是我的引用代码:
#include <string>
#include <sstream>
struct DataRow
{
std::string result;
float temp;
struct DataRow* next;
};
int main( )
{
DataRow* node = (DataRow*)malloc(sizeof(DataRow)); // Allocation of memory for struct here
int currentLoc = 0;
std::string dataLine = "HUUI 16:35:58 54.4 25.1 PDJ 1 MEME PPP PS$% sc3 BoomBoom SuperPower P0 123 25.86 0 11.1 1.0 50.0 W [2.0,0.28] 1.15 [5,6,100]";
std::string dataWord;
std::stringstream sDataLine( dataLine );
while ( sDataLine >> dataWord )
{
if( currentLoc == 0 )
{ node->result = dataWord; } // <-- Problem occurs here
else if ( currentLoc == 3 )
{ node->temp = atof(dataWord.c_str()); } // <-- This code works no problem on it's own
else
{ }
currentLoc++;
}
return 0;
}
代码在 node->result = dataWord
处失败。但是如果我注释掉这个 if 语句,只留下 node->temp=atof(dataWord.c_str());
代码就没问题了。
如何为 DataRow 结构的字符串成员实现正确的内存分配?
最佳答案
malloc
不确保调用 struct
成员的任何构造函数。 C++中的struct
与class
基本相同,唯一的区别是成员默认是public
而不是private
。因此,您应该新建
对象/结构,并在完成后删除
它。
关于c++ - 将字符串分配给结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051469/