c++ - 将字符串分配给结构元素

标签 c++

当我尝试将字符串值分配给结构成员时,我的程序崩溃了。 我怀疑结构中的成员(字符串类型)从未在内存中正确分配。

这是我的引用代码:

#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++中的structclass基本相同,唯一的区别是成员默认是public而不是private。因此,您应该新建对象/结构,并在完成后删除它。

关于c++ - 将字符串分配给结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051469/

相关文章:

c++ - 缓冲区或缓冲区大小不正确

c++ - 回调到单例类

c++ - 动态接受输入的数据类型

c++ - 有没有办法从 Excel 的公式栏中获取文本和光标位置?

c++ - 引用初始化表格

c++ - 用户定义的无序映射哈希函数

c++ - 如何正确地创建(和分配)仅由 C++ 中的抽象基已知的对象列表?

c++ - 如何在 VC++ 静态库中加载自定义二进制资源作为 dll 的一部分?

c++ - 在 Qt 中将一个小部件与另一个小部件交换

c++ - 在参数列表中使用表达式的意外输出