Sign in to follow this  
speedie

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


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this