storing pointers in a vector

Recommended Posts

ok I got a small function that's suppposed to create a series of pointers and store them in a vector, but I keep getting the unhandled expression 0x0000000000000005 or whatever it is. a bit a psuedo code to explain it.
mypointer *ptr;
vector<mypointer *> pointers;

for (int j=0; j<max; ++j)
{
ptr = Function_That_Returns_Pointer();
pointers.push_back(ptr);
}


is that not how I should do it?

Share on other sites
The pseudocode looks fine. If you want actual help, you'll need to post the actual source code and the actual error message.

Also, moved to For Beginners.

Share on other sites
it looks ok.
unless there is some problem with Function_That_Returns_Pointer();

Share on other sites
If you use the debugger, it will tell you exactly where the error is occuring, and it will give you lots of information to help you figure out why it is occuring.

Share on other sites
And 0x0000005 is an access violation, which usually means accessing a null pointer. Even when the function returns such a pointer, pushing it into the vector is totally valid (i.e. vector.push_back( NULL )). Therefore i suspect the problem is when you try to access the pointers stored in the vector later on.

Greetz,

illco

Share on other sites
when your returning your pointer, are you returning a pointer to a locally reference varible, or are you creating a new pointer?

mypointer *ptr=NULL;vector<mypointer *> pointers;for (int j=0; j<max; ++j){     ptr = Function_That_Returns_Pointer();     if (ptr) pointers.push_back(ptr);  //if not NULL     else break;}mypointer* Function_That_Returns_Pointer(){return new mypointer;}

If your creating the object locally, it goes out of scope on the return and you would be refenceding a NULL pointer.

If you do the above, make sure you delete each members of the vector when you go to exit the program.

for (int i=1;i<pointers.length();i++)    delete pointers[i];

Create an account

Register a new account

• Forum Statistics

• Total Topics
628328
• Total Posts
2982099

• 22
• 9
• 9
• 13
• 11