Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of string to structure element

Tags:

c++

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.

Here is my code for reference:

#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;
}

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.

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

like image 996
Splaty Avatar asked Dec 01 '25 11:12

Splaty


1 Answers

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.

like image 61
user268396 Avatar answered Dec 03 '25 02:12

user268396



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!