# Displaying a grid based map using C++ and sdl

I am trying to create a roguelike game using c++ and SDL. However, I am having trouble getting it to display the map, which is represented by a 2d array of a tile class.

Currently, my code is this:

for (int y = 0; y!=MAPHEIGHT; y++)
{
for (int x = 0; x!=MAPWIDTH 1; x++)
{
apply_surface( x * TILEWIDTH, y * TILEHEIGHT, mymap[x][y].image, screen );
}
}


However, running this code causes it to both dither for a while before opening the SDL window, and (usually) tell me there is an access violation. How can I display my map?

• is mapheight and mapwidth really the sizes of those arrays-1? Otherwise, you might want to try MAPHEIGHT-1 and MAPWIDTH-1. Also, have you tested and confirmed that mymap is correctly and completely filled? – TravisG Apr 15 '12 at 20:39
• @heishe: more to the point, something like < MAPHEIGHT is even better - semantically, the operation makes no sense for y >= MAPHEIGHT, not y != MAPHEIGHT, so it's best to code the condition as such. This is useful (for example) if you accidentally increment y beyond MAPHEIGHT within the loop: using a != condition misses that kind of case entirely, and the loop will happily keep churning on through all the invalid values > MAPHEIGHT until it either crashes, or the int wraps back around to MAPHEIGHT. – Mac Apr 15 '12 at 21:52

Make sure mymap is really a 2-dimensions array of size MAPWIDTH * MAPHEIGHT. E.g. if that's a plain old array of SDL_Surface pointers, its declaration should be as follows:

SDL_Surface* mymap[MAPWIDTH][MAPHEIGHT];


Then all the images stored in this array have to be loaded in memory before you call this code. That could be a simple loop, assuming you use SDL_image:

for (int x=0; x<MAPWIDTH; ++x)
{
for (int y=0; y<MAPHEIGHT; ++y)
{
mymap[x][y] = IMG_Load( some_function_that_gives_an_image_path(x, y) );

It's very likely that you'll want to share images between different tiles, so make sure you don't mess up and that every pointer in mymappoints to something real. A debugger might help spotting issues.