samedi 11 juillet 2020

Assigning std::vector to pointer inside a method

I want to create a method, which uses std::vectors to build up a collection of data, then do some operations on the data and finally, I want to pass the generated information through a pointer of a given argument as seen in this small example:

struct MyStruct
{
    int* list;
    int entry_count;
};




static MyStruct createList()
{
   vector<int> vectorList;
   MyStruct data;

   vectorList.push_back(1);
   vectorList.push_back(1);
   vectorList.push_back(1);
   vectorList.push_back(1);
   vectorList.push_back(1);

   data.list = &vectorList.front();
   data.entry_count = vectorList.size();
   return data;
}

int main(int argc, char** argv)
{
   MyStruct data;
   data = createList();

   return 1;
}

The problem is, after the method is closed, the vector is destroyed and the pointer shows nowhere.

How will I able to handle this problem in the correct way? So how can I assign this collection to a pointer without de-allocating it?

Aucun commentaire:

Enregistrer un commentaire