C++ return vector, can't figure out what's wrong
The following program keeps crashing and I can't figure out what's wrong. It seems that v is somehow not available in the main function..
#include <iostream>
#include <vector>
using namespace std;
vector<string> *asdf()
{
vector<str开发者_运维知识库ing> *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;
}
You want:
for (int i=0; i<(v->size()); i++) {
Your code is incrementing the pointer, not the index. which is a good reason to avoid dynamically allocating things, wherever possible.
You should change v++ to i++
v++ is the reason
精彩评论