Skip to main content
GameDev.net gamedev.net
🔒 Locked

Why doesn't this code work?

Started by Craazer Mar 4, 2003 at 1:24 PM 3 replies 200+ views
Original Post
Craazer
Craazer
I encountered a really wierd thing, when im trying push struct to vector and return pointer to the struct in the vector:
  
#include <iostream>
#include <vector>

using namespace std;

struct DING
{
 int k;
};

vector <DING> kkk;

DING* getsom()
{
 DING k; // temp

 k.k = 5;

 kkk.push_back(k);

 return &kkk.back(); // trying to return last element

}

int main()
{


DING* t1 = getsom();
DING* t2 = getsom(); // this will somehow ''overwrite'' t1''s address


     // t1 is invalid pointer!

cout<<(t1->k)<<"  "<<(t2->k)<<endl;

return 1;
}
  
But like you see from the comments that doesnt work, but why?
sjelkjd
sjelkjd
When you call push_back, vector may reallocate space and move elements. In particular, iterators and pointers may be invalidated. Instead, you should keep an index for each element and use that to refer to the object you want.
FunkyTune
FunkyTune
Just a thought... Wouldn''t a linked list be appropriate to use here?

/John
/John
Craazer
Craazer
quote:
Original post by sjelkjd
When you call push_back, vector may reallocate space and move elements. In particular, iterators and pointers may be invalidated. Instead, you should keep an index for each element and use that to refer to the object you want.


Ok, thanks. Just darn ironic that I had index system and I changed it to this pointer system :-/

Craazer
Craazer
quote:
Original post by FunkyTune
Just a thought... Wouldn''t a linked list be appropriate to use here?

/John


Maybe in this example but not in my purposes.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.