Reputation: 339
im new to both (memory allocation and classes)
im trying to make pixel map of (1 bit per pixel) so im trying to 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 what im trying to do is for example if i wanted pixel map of (100 x 100) .. i allocate 2d array of char [100][1+100/8] .. where the char stores 8 bits
pixmap::pixmap(int width, int height)
{
_width = width;
_height = height;
_rows = width/8+1;
pix_m = (char**) (calloc(height,_rows));
for (int x =0 ; x < _rows; x++)
{
pix_m[x] = (char*)calloc(_rows,sizeof(char*));
}
printf("%d\r\n",_rows);
}
this is my construct of the class ^^
and here where i should print a row of pixels:
void pixmap::printl(int y)
{
int pix;
for (int i = 0; i < _rows-1; i++)
{
for (int x= 0; x<8; x++)
{
pix = pix_m[y][i]&(0x01<<(7-x));
printf("%d",pix!=0);
}
}
int q = _width - (_rows-1)*8;
for (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 is when i try to print line bigger than 6 .. the program crashes .. shouldnt i be able to printl(0-99) ???
the code : http://pastebin.com/9X8r9PWe
Upvotes: 0
Views: 486
Reputation: 339
here i corrected the code :
class pixmap
{
private:
char _cols;
int _width, _height;
char **pix_m;
public:
pixmap(int , int);
uint8_t getpixel(int, int);
void printl(int);
};
pixmap::pixmap(int width, int height)
{
_width = width;
_height = height;
_cols = width/8+1;
pix_m = (char**) (calloc(height,sizeof(char)*_cols));
for (int x =0 ; x < height; x++)
{
pix_m[x] = (char*)calloc(_cols,sizeof(char));
}
printf("%d\r\n",_cols);
for (int i=0; i < 100; i++)
{
for (int j=0; j<_cols; j++)
{
pix_m[i][j] = i;
}
}
}
Upvotes: 1
Reputation: 5093
You usage of calloc
function is wrong.
pix_m = (char**) (calloc(height,_rows));
This code does not work properly. As far as I can see you want _rows
element vector of char*
. It actually allocates height elements each of size equivalent to sizeof(_rows)
thus sizeof(char)
in your case. Instead you should invoke
calloc(_rows, sizeof(char*));
Your second call should be
pix_m[x] = (char*)calloc(height,sizeof(char));
EDIT: after analysing rest of your code it seems like you messed it up a bit and thus it should be:
pix_m = (char**) (calloc(height,sizeof(char*)));
for (int x =0 ; x < height; x++)
{
pix_m[x] = (char*)calloc(_rows,sizeof(char));
}
Upvotes: 1