C++ 字符串对结构元素的赋值
当我试图将字符串值分配给结构的成员时,我的程序崩溃。 我怀疑结构中的成员(字符串类型)从未在内存中正确分配 以下是我的代码供参考:C++ 字符串对结构元素的赋值,c++,C++,当我试图将字符串值分配给结构的成员时,我的程序崩溃。 我怀疑结构中的成员(字符串类型)从未在内存中正确分配 以下是我的代码供参考: #include <string> #include <sstream> struct DataRow { std::string result; float temp; struct DataRow* next; }; int main( ) { DataRow* node = (DataRow*)mal
#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;
}
#包括
#包括
结构数据行
{
std::字符串结果;
浮子温度;
结构数据行*下一步;
};
int main()
{
DataRow*节点=(DataRow*)malloc(sizeof(DataRow));//此处为结构分配内存
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,6100]”;
字符串数据字;
std::stringstream sDataLine(数据线);
while(sDataLine>>dataWord)
{
如果(当前位置==0)
{node->result=dataWord;}//temp=atof(dataWord.c_str());}//< p> <代码> MaloC/<代码>不能保证您的代码的成员的任何构造函数>结构> <代码>。在C++ >代码>结构> <代码>基本上与<代码>类< /C> >相同,唯一的区别是默认情况下,成员是代码>公用< /代码>,而不是<代码>私下<代码>。因此,您应该<代码>新< /COD>对象/Stutt,和 >删除/ <代码> >完成。 < p>分配<代码>节点< /C> >的方式是错误的:如果您想在C++中动态分配非POD类型,则需要使用<代码>新< /C> >,因为它将调用所需构造函数(随后调用“代码>删除”/代码>适当的时候)。
但分配自动实例可能更简单:
DataRow node;
如果确实需要指针,请确保查看,尤其是和。另请参见。您必须创建一个新结构,而不使用malloc
因此,请使用:
DataRow* node = new DataRow;
您还应注意清理它,如下所示:
delete node;
如果您不想从堆中分配它,您也可以这样做:
DataRow node;
< C++ >使用“新”而不是“Malc”。使用MALOC不运行类的构造函数,所以字符串没有初始化。 < P>所以在回答你的问题之前,我只想说除非你被迫,否则不应该在C++中使用Malloc。这个答案解释为什么很好。
换了这条线
DataRow* node = (DataRow*)malloc(sizeof(DataRow));
对此
DataRow* node = new DataRow;
将解决您的问题您从不检查malloc
的返回值。我在Windows上使用MinGW时不会发生崩溃。您使用的编译器是什么?在哪里构造了node->result
?您必须有std::string
才能在赋值的左侧使用它!malloc()
不保证所分配内存的内容被初始化为任何内容。您可以使用calloc()
,这至少可以将内存归零。但是使用new
是正确的方法。class
和struct
之间的另一个区别(在本例中不相关):struct
的基类默认为public
。