I try to initialize the data for the bitmap image (header info and pixels bits ) through the following function:

 VOID MakeBitmap (BITMAPINFO* info, BYTE *bits, int w, int h) { info = (BITMAPINFO*)new BYTE[w * h * 3 + sizeof(BITMAPINFOHEADER)]; ZeroMemory(info, w * h * 3 + sizeof(BITMAPINFOHEADER)); BITMAPINFOHEADER* ph = &info->bmiHeader; ph->biSize = sizeof(BITMAPINFOHEADER); ph->biWidth = w; ph->biHeight = h; ph->biPlanes = 1; ph->biBitCount = 24; ph->biSizeImage = w * h * 3; bits = (BYTE*)info + sizeof(BITMAPINFOHEADER); } 

Initializing everything is fine. But as soon as I try to get access to the element of the array bits[i] , the program crashes as if there is nothing there. It also does not work if you allocate a separate memory block for bits .

What is the problem?

  • one
    Where does the program fly? I would bet that you are changing the local copy of bits , and what is passed to the function does not change - check it yourself using a debugger or debug output of the contents of variables. Business for 5 minutes. The info is the same. There are two solutions. Both lead to a change in the prototype f-tion: VOID MakeBitmap (BITMAPINFO** info, BYTE** bits, int w, int h) or VOID MakeBitmap (BITMAPINFO*& info, BYTE*& bits, int w, int h) And specify what are in-parameters, and what is out. - gecube
  • There is no problem with info. A pointer is passed, and an array of data is created using it. This is the correct use of the pointer. - Andrey Golikov

1 answer 1

In such a description

 VOID MakeBitmap (BITMAPINFO* info, BYTE *bits, int w, int h) 

Bits is a pointer to a memory region, through it you can change this region, but you cannot change the pointer itself. When you exit the function, the passed bits (its value) will remain unchanged, although you have changed it in the function. If I understand your idea correctly, you need to do

 VOID MakeBitmap (BITMAPINFO* info, BYTE **bits, int w, int h) ... *bits=(BYTE*)info+sizeof(BITMAPINFOHEADER); 

So after exiting the function, you will have a new pointer to the created memory. Call:

 BYTE * my_bits; ... MakeBitmap(... &my_bits ...); 

but it seems to me that architecturally it is better to solve with a class with a field of bits inside, and normal fields - a header