Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using pointer to vector properly

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading