Splaty
Splaty

Reputation: 634

I need help explaining the behaviour of this code

I've been having a lot of trouble with the concept of an array of struct. I put together some basic code. The output from this code was not what I expected at all. I was wondering if someone could explain why this code behaves the way it does.

#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>

struct DataRow
{
    std::string word1;
    std::string word2;
    std::string word3;  
};

void getRow( std::string line, DataRow** dataRowPointer, int index )
{
    std::stringstream sline(line);
    std::string word;

    int wordIndex = 0;

    *dataRowPointer = new DataRow[3];

    while( sline >> word )
    {
        if ( wordIndex == 0 )
        {   (*dataRowPointer)[index].word1 = word;  }
        else if ( wordIndex == 1 )
        {   (*dataRowPointer)[index].word2 = word;  }
        else 
        {   (*dataRowPointer)[index].word3 = word;  }

        wordIndex++;
    }
}

int main( )
{
    int index = 0;  

    std::string line1 = "This is line";
    std::string line2 = "Two is magic";
    std::string line3 = "Oh Boy, Hello";

    DataRow* dataRowPointer;

    getRow( line1, &dataRowPointer, index );
    index++;
    getRow( line2, &dataRowPointer, index );
    index++;
    getRow( line3, &dataRowPointer, index );

    for( int i = 0; i < 3; i++ )
    {
        std::cout << dataRowPointer[i].word1 << dataRowPointer[i].word2 << dataRowPointer[i].word3 << "\n";
    }
    return 0;
}

There are 3 strings. I want to separate each individual word within each string and store them into a structure. I have an array of structures to store them. The size of the array is 3 (since there are 3 lines). I do not set the pointer in main, I set the pointer in my function. From there I start collecting my words to store.

I obtain this output:

(blank line)    
(blank line)    
OhBoy,Hello

My question is, where did my first two structures go?

Upvotes: 2

Views: 109

Answers (1)

Gabriele Giuseppini
Gabriele Giuseppini

Reputation: 1581

Your getRow is re-allocating the DataRow array on each invocation, and thus you're losing the results of the first two invocations. Move the allocation into your main().

Upvotes: 5

Related Questions