Advertisement Jump to content
Sign in to follow this  

vector in stl

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

Since local variables are destroyed when exit the function where they are defined, you can't return a pointer or a reference to a local variable and expect your code to work.

Share this post

Link to post
Share on other sites
Original post by luasitdown
int* getvalue(float time)
vector<int> v;
return &v[0];

this not work.

how to return pointer?

Well, the way your doing it there, it's really not a good idea because the pointer you're returning is going to point to invalid memory.

Once the function exits or returns, the vector you created there will no longer exist, and the pointer will point to something it shouldn't. Pointing to an item in a vector is a bad idea, because (If I remember correctly) STL makes no guarentee's that a pointer to an item in a vector won't be changed internally at a later point. That is, again, you'll have a pointer to some place it shouldn't be.

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
A pointer into an element in a vector is invalidated just like an iterator into an element in a vector is. In fact the iterator might be a pointer, which is upto the implementation of the standard library.

One other little thing wrong with the code snippet was that the vector didn't actually contain anything so the access to element 0 was wrong in the first place.

// ville

Share this post

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

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!