• Advertisement

Archived

This topic is now archived and is closed to further replies.

Why doesn't this code work?

This topic is 5438 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

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?

Share this post


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

Share this post


Link to post
Share on other sites
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 :-/

Share this post


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

Share this post


Link to post
Share on other sites

  • Advertisement