Home c++ Write a dynamic array in a binary file C++

Write a dynamic array in a binary file C++

Author

Date

Category

Trying to function, which will create a BMP file.

The basic structure:

# pragma pack (push, 1)
  TypeDef struct {
    int16_t bfType;
    uint32_t bfSize;
    int16_t bfReserved1;
    int16_t bfReserved2;
    uint32_t bfOffBits;
  } BITMAPFILEHEADER;
#pragma pack (pop)
#pragma pack (push, 1)
  TypeDef struct {
    uint32_t biSize;
    int32_t biWidth;
    int32_t biHeight;
    int16_t biPlanes;
    int16_t biBitCount;
    uint32_t biCompression;
    uint32_t biSizeImage;
    int32_t biXPelsPerMeter;
    int32_t biYPelsPerMeter;
    uint32_t biClrUsed;
    uint32_t biClrImportant;
  } BITMAPINFOHEADER;
#pragma pack (pop)
#pragma pack (push, 1)
  TypeDef struct {
    int8_t rgbBlue;
    int8_t rgbGreen;
    int8_t rgbRed;
    int8_t rgbAplha;
  } RGBQUAD;
#pragma pack (pop)

Sami variables and functions:

BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
RGBQUAD * palette;
void Create (const char * fname) {
  ofstream out (fname, ios :: binary);
  palette = new RGBQUAD [16];
  // Here missed filling palette write, but filled to the test here so = new RGBQUAD [16] {{255,255,255,0}, {}};
  bfh = {};
  bih = {};
  bfh.bfType = 0x4d42;
  out.write ((const char *) & amp; bfh, sizeof (bfh));
  out.write ((const char *) & amp; bih, sizeof (bih));
  // Here I have tried a lot of options, but none of them worked.
}

As written in binary palette? If you make it a static array and write

out.write ((const char *) & amp; test, sizeof (test));

everything will work perfectly, but still need a dynamic array. Please tell me how to realize, what I need for understanding will be glad if you explain how it works.

Here is an example:

palette = new RGBQUAD [16] {
    {0,0,0,0}, {0, 128,0,0}, {0, 0, 128, 0}, {} 0,128,128,0,
    0,0,0,128 {}, {} 0,128,0,128, 0,0,128,128 {}, {} 0,128,128,128,
    0,192,192,192 {}, {} 0,255,0,0, 0,0,255,0 {}, {} 0,255,255,0,
    0,0,0,255 {}, {} 0,255,0,255, 0,0,255,255 {}, {0, 255, 255, 255}
  };
out.write ((const char *) palette, sizeof (RGBQUAD) * 16);

But what happens (sorry for the quality):

Obviously, this is not what I expected to see.

I looked up and it turns out that the palette is initialized not like I have and all the elements are equal to -51. I do not know yet what was going on.


Answer 1, Authority 100%

The problem is not in the record, and initialize an array of structures using c initializer list, and it’s interesting, because I just thought that this design should work ..

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions