c style string and dynamic allocation in c++ -
i must implement bunch of methods allocates, modify , free 2d array of c-style string. cannot use string nor vectors nor stl container.
getnewmat :
char*** getnewmat(int w, int h){ char*** newmat = new char**[h]; for(int = 0 ; < h ; i++){ newmat[i] = new char*[w]; for(int j = 0 ; j < w ; j++) newmat[i][j] = null; } return newmat; }
fillmat
void fillmat(char***mat, int x, int y, char* newel){ mat[y][x] = newel; //this produce segfault (even index) }
showmat :
void showmat(char*** mat, int w, int h){ for(int = 0 ; < h ; i++){ for(int j = 0 ; j < w ; j++) cout << mat[i][j]; } cout << endl; }
so, can please tell me what's wrong this?
in fillmat
method this:
mat[y][x] = newel;
where x
, y
dimensions of 2 ranks of array. line cause segmentation fault because you're going outside bounds of array. mat
indexed 0 length - 1
, setting x
, y
going 1 outside bounds of array.
maybe meant loop through , set them:
for (int = 0; < y; ++i) { (int k = 0; k < x; ++k) mat[i][k] = newel; }
moreover, inside showmat
function have this:
cout << showmat[i][j];
i think meant mat
:
cout << mat[i][j];
Comments
Post a Comment