Search code examples
c++stdvector

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?


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>>;
    

    The intent of the above code was to show how an address of an object could be obtained, either via the address of & or the new operator.

    When it comes to 'best practice', i would say, avoid pointers use references. But when an allocation is needed, then

    • one could wrap the pointer either into an unique_ptr or shared_ptr object (guaranteed deallocation of the allocated memory block, e.g. in case of an uncaught exception)

    e.g.

    //allocate a single vector<int> and insert the values 1, 2, 3
    auto my_vec_ptr = std::make_unique<std::vector<int>>(1, 2, 3);
    //(*my_vec_ptr).push_back(42); //dereference pointer and add the value 42
    
    //allocates an array of 5 vector<int>
    auto my_vec_array = std::make_unique<std::vector<int>[]>(5);
    //my_vec_array[0].push_back(42); //adds 42 to the first vector
    
    • or use a container, like vector, map, etc.

    e.g.

    //constructs the vector with 5 default-inserted instances of vector<int>
    std::vector<std::vector<int>> my_vec_of_vec{5};
    //my_vec_of_vec[0].push_back(42); //adds 42 to the first vector
    //my_vec_of_vec.push_back(std::vector<int>{1,2,3}); //add a new vector to the list