动态存储器阵列使用逻辑循环

时间:2013-11-12 23:11:10

标签: c++ loops memory dynamic

我有一个与动态记忆有关的问题。我已经非常放弃使用它并现在使用向量,但仍然想知道为什么以下类型的代码经常给我带有错误内存分配的运行时错误。有没有办法用动态内存做到这一点?

这个想法基本上是根据某些条件使用循环来增加数组的大小。如上所述,我现在只使用vector.push_back(),但我想发布并查看是否有任何见解。

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <new>

int main()
{
    ifstream infile.open("file.txt");

    string str1, str2; stringstream os;

    int length;
    string *vecarr = new string[length];
    length = 0;

    while(!infile.eof())
    {
        getline(infile,str1);
        if(str1.find("expression") != string::npos)
        {
            length++;
            vecarr[length-1] = str1;
        }
    }

    infile.close();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

length在表达式new string[length]中未初始化,因此这是纯粹的未定义行为。您不得阅读未初始化的int变量。