I’m a C# programmer having problems with messy pointers and I just can’t find out what the mistake is.. I could use some help with the list
So basically I have something like a stack of cards and these cards are saved in a list. I just want to take the upper most and return it to the function. I could use pop_back() but the last card has to stay as it is because it is the cardback (I’m making it later with textures and stuff)
Card * CardStack::HandOut()
{
if (m_Stack.size() > 1)
{
list<Card *>::iterator it = m_Stack.end();
advance(it, -2);
Card *ret = *it;
Card tmp = *ret;
Card *tmpp = &tmp;
m_Stack.remove(ret);
return tmpp;
}
return NULL;
}
So I want to always pop the second last Card back.
I’m sure its a total beginner mistake 🙁
You are returning a pointer to a local variable,
that doesn’t exist anymore after the function exited. So when you use the pointer later, you invoke undefined behaviour.
You should not bother with
tmpandtmpp, returningretought to do it, theremovedoesn’t destroy the card, it just removes (the pointer to) it from the stack.