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;
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With