C++ pointer to vector
Solution 1
You never allocate the vector:
vector<int> *te = new vector<int>;
Also, you don't need dynamic allocation. A cleaner way is with automatic storage:
int main()
{
vector<int> te;
te.push_back(10);
cout<<te.size()<<endl;
return 0;
}
Solution 2
vector<int> *te;
te->push_back(10);
You have declared a pointer to a vector
; you have not initialized it to point to a valid piece of memory yet. You need to construct a new vector using new
.
vector<int> *te = new vector<int>();
You should however not do this. There are very few reasons to maintain a pointer to a vector, and you just made it completely ineffective at managing its own internal memory.
Read a little bit about RAII. This is a technique used to manage dynamically allocated memory via the lifetime of an object. The vector
uses this method to clean up its internal, dynamically allocated storage when it goes out of scope.
Maintaining a pointer to the vector prevents it from working correctly, relying on you to call delete
yourself, essentially nullifying one major benefit of using a vector
over an array in the first place.
Solution 3
you have to first allocate place for the pointer before starting to use it .
vector<int> *te = new vector<int>();
insert this line into your code just after the vector<int> *te;
Note that
If you were to trying to access already defined vector with an pointer you would not have to allocate place for the pointer.
For example;
vector<int> foo={1,2,3,4,5};
vector<int> * te=&foo;
te->push_back(6); // its legal.
Mukesh
Updated on November 24, 2021Comments
-
Mukesh over 2 years
I have to insert elements into a pointer to a vector.I have written the following code but it is giving segmentation fault. Could someone please point out what are the errors in this code or how can we do this alternatively.
int main() { vector<int> *te; te->push_back(10); cout<<te->size()<<endl; return 0; }