1

i have written this structure:

struct bmpheader {
    unsigned char magic[2];
    unsigned int fsize;
    unsigned int unused;
    unsigned int pixdata_offset;
    unsigned int headersize;
    unsigned int width;
    unsigned int height;
    unsigned short planes_color;
    unsigned short bpp;
    unsigned int compression;
    unsigned int sizeofpix;
    unsigned int resolutionx;
    unsigned int resolutiony;
    unsigned int colors;
    unsigned int imp_colors;
};

And i have a problem with sizeof function. When im counting on my fingers, its every time 54 bytes for me. sizeof function gives me every time 56. Why? The problem is with unsigned char array, when i remove magic[2] array, sizeof is 52? sizeof(header.magic) is shown as 2. As far i know unsigned char is 1-byte type?

Thanks in advance for responses.

marcin

7
  • 1
    You can count to 54 on your fingers? Commented Feb 12, 2012 at 20:00
  • 1
    The compiler is inserting padding into your struct layout to ensure better alignment of the fields. This padding will be between the two magic chars and the first int to make sure that the ints all fall on 4 byte boundaries. Commented Feb 12, 2012 at 20:01
  • 1
    @SethCarnegie, I can count up to 1024 on my fingers Commented Feb 12, 2012 at 20:02
  • 1
    the question should be: Why is this a problem? Commented Feb 12, 2012 at 20:04
  • 1
    @Lol4t0: I can only count up to 1023 on mine. Commented Feb 12, 2012 at 20:54

1 Answer 1

1

Because an int (on your machine) must be, or is more efficient when, placed on a 4-byte address. The compiler will insert two bytes of padding after the char array.

Sign up to request clarification or add additional context in comments.

3 Comments

Must is too strong. Compilers often choose to do that for performance reasons rather than necessity.
Ah. Great. Good to know. Thank you :P Now its working ;p And, i have a little question again (and very easy i think). I have unsigned char magic[2]; How to write there "BM" at once, not by magic[0] = 'B', magic[1] = 'M'? I tried with magic = "BM"; or magic = {'B', 'M'};, both didnt work...
You cannot assign to an array. You can however use initializer syntax. That's going to mean writing a struct initializer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.