views:

113

answers:

3

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<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;
}
+7  A: 

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.

anon
Using an iterator is even preferable IHMO
Little Bobby Tables
@Little Depends - for vectors operator[] is usually shorter, clearer, and might even be a tiny bit faster.
anon
It might be slower as well. For example if the runtime performs bounds checking like MSVC does by default in some versions.
jalf
+3  A: 

You should change v++ to i++

+2  A: 

v++ is the reason

Vorber