Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer to vector

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;
 }
like image 471
Mukesh Avatar asked Nov 27 '22 17:11

Mukesh


2 Answers

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;
}
like image 151
Luchian Grigore Avatar answered Dec 08 '22 00:12

Luchian Grigore


 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.

like image 41
Ed S. Avatar answered Dec 08 '22 00:12

Ed S.