• Advertisement
Sign in to follow this  

storing pointers in a vector

This topic is 4013 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement