c++ - Segmentation fault -
#include <iostream> using namespace std; void initializemap(int mapsizex, int mapsizey, int map[][10]) { // map details: // 0 = # (wall) // 1 = space (free space) // 2 = x (player) for(int x = 0; x < mapsizex; x++) { map[x][0] = 0; } for(int y = 0; y < (mapsizey - 2); y++) { map[0][y] = 0; for(int x = 0; x < (mapsizex - 2); x++) { map[x][y] = 1; } map[mapsizex][y] = 0; } for(int x = 0; x < mapsizex; x++) { map[x][mapsizey - 1] = 0; } } void paintmap(int mapsizex, int mapsizey, int map[][10]) { for(int y = 0; y < mapsizey; y++) { for(int x = 0; x < mapsizex; x++) { switch(map[x][y]) { case 0: cout << "#"; break; case 1: cout << " "; break; case 2: cout << "x"; break; } cout << map[x][y]; } cout << endl; } } int main() { int mapsizex = 10; int mapsizey = 10; int map[10][10]; initializemap(mapsizex, mapsizey, map); paintmap(mapsizex, mapsizey, map); cout << endl << endl; return 0; } my code compiles fine without errors when try run it, says "segmentation fault". i've done research , don't understand why because don't use pointers @ all. how fix this? compile using g++ , run typing ./main in terminal.
map[mapsizex][y] = 0;
this illegal. valid values of index run 0 mapsizex - 1.
the line should be:
map[mapsizex][y] = 0; one assumes desired output?
#0#0#0#0#0#0#0#0#0#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0#0#0#0#0#0#0#0#0#0
if so, have number of other off-by-one errors in initializemap function. instead of:
for(int y = 0; y < (mapsizey - 2); y++)
and
for(int x = 0; x < (mapsizex - 2); x++)
you should use
for(int y = 1; y < (mapsizey - 1); y++) and
for(int x = 1; x < (mapsizex - 1); x++) respectively.
btw, here's cleaner way write initializemap:
template<int mapsizex, int mapsizey> void initializemap(int (&map)[mapsizex][mapsizey]) { for( int y = 0; y < mapsizey; y++ ) { for( int x = 0; x < mapsizex; x++ ) { if (x == 0 || x + 1 == mapsizex || y == 0 || y == mapsizey) map[x][y] = 0; else map[x][y] = 1; } } } and can call just
initializemap(map); no need pass size, compiler figure out automatically.
Comments
Post a Comment