I have a pointer to vector setup in my IDE but i dont think im doing it right cuz everytime i try to push_back data into it the program crashed at that point in the code.
For example:
std::vector<int> a; std::vector<std::vector<int> > *a1;
a.push_back(3);
a1->push_back(a); // Right here the program crashes with no indication prior to execution that there was an error.
I’ve seen some other users of this site have pointers of vectors initialized but now that i think about it i dont recall them really accessing them to put data in or to edit later. Maybe thats why im stuck at this point getting Crashes. So could anyone explain why it and happens how to do pointer to vectors properly. I want to access vector a1 like so:
cout<<" value is: "<<(*a1)[0][0] + 4 <<endl; // I cant even reach this far when the program runs
What about this im not getting right?
>Solution :
a is a vector. Below is a declaration (and definition) of a:
std::vector<int> a;
a1 is a pointer to a vector. Below is a declaration and definition of a1, but the pointer doesn’t point at a defined location (thanks to @user4581301, for pointing that out):
std::vector<std::vector<int> > *a1;
In order to define the value in a1, one could either assign the address of an already existing vector or allocate a new vector via new, e.g.
//pre defined vector
std::vector<std::vector<int>> a;
//assign address of a to a1
std::vector<std::vector<int>> *a1 = &a;
//or allocate a new vector
std::vector<std::vector<int>> *a2 = new std::vector<std::vector<int>>;