While searching up methods of detecting multiple keys at once in SDL 2, I came across this piece of code for SDL 1.x:
//author: Rob Loach
// Global key buffer
bool keys[256];
while(SDL_PollEvent(&mainEvent))
{
if(mainEvent.type == SDL_KEYDOWN)
{
keys[mainEvent.key.keysym.sym] = true;
}
else if(mainEvent.type == SDL_KEYUP)
{
keys[mainEvent.key.keysym.sym] = false;
}
}
I tried implementing it in SDL2 and a std::array<bool, 256>, but I had Segmentation fault: 11 with the up button.
That's when I looked at this: https://wiki.libsdl.org/SDLKeycodeLookup.
Most of the 'special' keys including arrow, function, symbols, and so on have decimal representations in the billions.
Even with the simple code printf("%d\n", e.key.keysym.sym); on, say the up button gives:
1073741906
Segmentation fault: 11
I am on a Mac, if it makes any difference with the error codes.
So, what solutions are there to this in SDL 2?
First of all,
bools don't default to anything inC++, you need to initialize them. The fact that they appear to always betrueis that they'rebytein size. Which means they have a size between0and255inclusive. Only0would meanfalseso its a255 / 256chance oftrue.As for your solution, you would simply define your
std::mapas this :An
std::mapis initially empty, so you need to check that the items actually exists when you try to look it up.When you try to set an item, it will automtically get created if it doesn't exists :
So the fact the
std::mapis initially empty means you don't need to fill it. You can if you want to, but it's not required like it is with an array.