我有一个与动态内存相关的问题。我几乎已经放弃使用它,现在改用 vector ,但仍然很想知道为什么以下类型的代码经常给我一个内存分配错误的运行时错误。有没有办法用动态内存来做到这一点?
这个想法基本上是根据某些条件使用循环来增加数组的大小。如前所述,我现在只为此使用 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;
}
最佳答案
length
在表达式 new string[length]
中未初始化,因此这是普通的未定义行为。您不得读取未初始化的 int
变量。
关于c++ - 使用逻辑循环的动态内存阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19941895/