storing pointers in a vector

Started by
4 comments, last by d4m 17 years, 1 month ago
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?
-----------------------------------------------The ZoloProject
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.
it looks ok.
unless there is some problem with Function_That_Returns_Pointer();
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
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.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
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
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;

This topic is closed to new replies.

Advertisement