我需要帮助解释此代码的行为
I need help explaining the behaviour of this code
我对结构数组的概念有很多麻烦。我整理了一些基本代码。这段代码的输出根本不是我预期的。我想知道是否有人可以解释为什么这段代码的行为方式。
#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()
中。
相关文章:
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 有人能为我解释一下C++代码吗
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 有人可以解释一下这段代码如何能够反转字符串
- 有人可以向我解释一下这段代码的作用吗?
- 有人可以详细解释这个回文代码是如何工作的吗?
- 如何在 C++11 中解释静态代码
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 我不完全确定此代码的行为.有人可以向我解释一下吗?
- 有人可以解释我这个代码吗?它给出与我们输入的数字相反
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 解释以下宏代码的 O/P
- 如何解释 IDA Pro 生成的这些代码?
- 有人能给我解释一下下面的模板代码吗
- 按位 - 代码解释
- 有人可以根据此代码解释起床和降低语法
- 用于人脸检测的Haar级联xml文件代码解释OpenCV
- 代码解释 C++ [结构 / 两个 diamentinal 数组 / 指针]
- int到二进制代码解释C++
- c++代码解释