multidimensional array - c++ dynamic allocation (pixel map) -


im new both (memory allocation , classes)

im trying make pixel map of (1 bit per pixel) im trying make char array in dynamic memory allocation..

class pixmap { private:     char _rows;     int _width, _height;     char **pix_m; public:     pixmap(int , int);     uint8_t getpixel(int, int);     void printl(int);  }; 

so im trying example if wanted pixel map of (100 x 100) .. allocate 2d array of char [100][1+100/8] .. char stores 8 bits

pixmap::pixmap(int width, int height) {     _width = width;     _height = height;     _rows = width/8+1;      pix_m = (char**) (calloc(height,_rows));     (int x =0 ; x < _rows; x++)     {            pix_m[x] = (char*)calloc(_rows,sizeof(char*));     }      printf("%d\r\n",_rows); } 

this construct of class ^^

and here should print row of pixels:

void pixmap::printl(int y) {     int pix;     (int = 0; < _rows-1; i++)     {         (int x= 0; x<8; x++)         {             pix = pix_m[y][i]&(0x01<<(7-x));             printf("%d",pix!=0);         }     }     int q = _width - (_rows-1)*8;     (int x= 0; x<q; x++)     {         pix = pix_m[y][_rows-1]&(0x01<<(7-x));         printf("%d",pix!=0);     } } 

and in main function :

int main() {     pixmap img(50,100);     img.printl(1);      getch(); } 

the problem when try print line bigger 6 .. program crashes .. shouldnt able printl(0-99) ???

the code : http://pastebin.com/9x8r9pwe

you usage of calloc function wrong.

pix_m = (char**) (calloc(height,_rows)); 

this code not work properly. far can see want _rows element vector of char*. allocates height elements each of size equivalent sizeof(_rows) sizeof(char) in case. instead should invoke

calloc(_rows, sizeof(char*)); 

your second call should be

pix_m[x] = (char*)calloc(height,sizeof(char)); 

edit: after analysing rest of code seems messed bit , should be:

pix_m = (char**) (calloc(height,sizeof(char*))); (int x =0 ; x < height; x++) {        pix_m[x] = (char*)calloc(_rows,sizeof(char)); } 

Comments