字符串到结构元素的分配 [英] Assignment of string to structure element

查看:87
本文介绍了字符串到结构元素的分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My program crashes when I try to assign a string value to a member of a structure. My suspicion is that the member (of type string) within the structure was never properly allocated in memory.

这是我的代码参考:

#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()); 代码没有问题。

The code fails at node->result = dataWord. But if I comment out this if statement, and leave only the node->temp=atof(dataWord.c_str()); the code works no problem.

如何为DataRow结构的字符串成员实现合适的内存分配?

How do I achieve proper memory allocation for the string member of the DataRow struct?

推荐答案

malloc 不能确保您的 struct 的成员的任何构造函数被调用。在C ++ struct 基本上与 class 相同,唯一的区别是成员 public ,而不是 private 。所以你应该 new 的对象/结构,和删除完成后。

malloc doesn't ensure any constructors of the members of your struct are called. In C++ struct is basically the same as class, the only difference is that members are public by default rather than private. So you should new the object/struct, and delete it when done.

这篇关于字符串到结构元素的分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆