Nil*_*ils 0 c++ memory-management
以下程序不断崩溃,我无法弄清楚是什么问题.似乎v在某个主要功能中不可用..
#include <iostream>
#include <vector>
using namespace std;
vector<string> *asdf()
{
vector<string> *v = new vector<string>();
v->push_back("blah");
v->push_back("asdf");
return v;
}
int main()
{
vector<string> *v = NULL;
v = asdf();
for (int i=0; i<(v->size()); v++) {
cout << (*v)[i] << endl;
}
delete v;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
你要:
for (int i=0; i<(v->size()); i++) {
Run Code Online (Sandbox Code Playgroud)
您的代码正在递增指针,而不是索引.这是避免动态分配事物的一个很好的理由,只要有可能.