我需要帮助解释此代码的行为

I need help explaining the behaviour of this code

本文关键字:代码 解释 帮助      更新时间:2023-10-16

我对结构数组的概念有很多麻烦。我整理了一些基本代码。这段代码的输出根本不是我预期的。我想知道是否有人可以解释为什么这段代码的行为方式。

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

有 3 个字符串。我想将每个字符串中的每个单词分开并将它们存储到一个结构中。我有一系列结构来存储它们。数组的大小为 3(因为有 3 行(。我不在 main 中设置指针,我在函数中设置指针。从那里我开始收集我的话来存储。

我得到这个输出:

(blank line)    
(blank line)    
OhBoy,Hello
我的

问题是,我的前两个结构去哪儿了?

您的getRow在每次调用时重新分配 DataRow 数组,因此您将丢失前两次调用的结果。将分配移动到您的main()中。