开发者

C++ return vector, can't figure out what's wrong

开发者 https://www.devze.com 2023-01-11 15:20 出处:网络
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..

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

0

精彩评论

暂无评论...
验证码 换一张
取 消