Skip to main content
gamedev.net
🔒 Locked

return vectorstring from function

Started by fredrum Mar 26, 2009 at 5:28 AM 2 replies 550+ views
Original Post
fredrum
fredrum
Hello, I want to pass a vector to a function as a pointer, manipulate it and pass it back out, but can't get it to work. I have found postings about it on the web but nothing seems to help. This is how my code looks. Simplified. // class.h class hitList { vector names; } // function.h void AddOneNameFunc(vector * names); //function.cpp void AddOneNameFunc(vector * names) { // ...manipulate names } I then try to call the function like so: // class.cpp void hitList::WhenAngry() { AddOneNameFunc(&names); } It compiles and links but when I try and trigger the function it crashes and the XCode debugger kicks in. Strangely(for me), I can get it to work if I do the following. Although I can't do this, I need to use my class variable. void hitList::WhenAngry() { vector tmpNames; vector* pTmpNames = &tmpNames AddOneNameFunc(pTmpNames); } EDIT: I have also tried casting names as, vector* and then passing to function without the '&'. But I still get a crash. Can anyone see what I am getting wrong? Any help appreciated. cheers fred
Evil Steve
Evil Steve
1. What is the exact error? That code looks fine to me, the only thing I see that could be causing a problem is if your this pointer is invalid (I.e. your hitList instance is null or deleted).
2. Since you're using C++, it's preferable to use references. Then your code becomes:
// class.hclass hitList{   std::vector<std::string> names;};void AddOneNameFunc(std::vector<std::string>& names){}void hitList::WhenAngry(){   AddOneNameFunc(names);}
Molle85
Molle85
I only want to add that the XCode debugger (and XCode in general) is awful,
and you should never trust it 100%...

if you come up with strange crashes you should try rebuilding the project,
most of the time that solves it.
fredrum
fredrum


Steve, thanks for your reply!
And you were absolutely right, I tried to use 'hitList' without having instantiated(?) it first.

I never tried to use it before it was instantiated by a different part of the program before.

Thanks a lot.

And molle85, it might be that XCode is not great, I wouldn't know.
(yeah that previous build problem thing is crap though)

I'm pretty awful myself so its a good match! ;)

cheers
fred

Topic Locked

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

Sign in to reply to this topic.