Sturcture size

Let say I have a structure like

struct
{
char ch1;
char ch2;
};

The sizeof() the structure is 2 but when…

struct
{
char ch;
int num;
};

The sizeof() the structure is not
sizeof(char) + sizeof(num),
it’s sizeof(int) * 2 ??!!

I just hate this because I can’t directly read image file header, I have to read the value one by one.

  1. This is offtoppic (i hate guys saying this )
  2. That is because your compiler optimises the code for speed, so it aligns your data to 4byte blocks…
  3. solving your problem (dirt way, i think):
    struct{
    char dummy[3];//this space is unused like in your code
    char ch;
    int num
    } x;
    //by reading data you have to correct the pointer:
    char *ptr= (char *)&x + 3;

[This message has been edited by T2k (edited 12-11-2001).]

Another option is to use a pragma to disable the alignment optimization for that structure.

Thanks for T2K’s “dirty” method. But I prefer just to disable it, but how??

This is for MSVC. Might work for other compiler aswell.

#pragma pack(push, 1)
// your structure goes here
#pragma pack(pop)

1 after the push means one byte alignment.

You can of course define as many structures as you want inside the pack-block.

What’s the differences between

#pragma pack(1)
//…

and

What’s the differences between

#pragma pack(1)
//structure

and

#pragma pack(push, 1)
//structure
#pragma pack(pop)

Originally posted by Questions Burner:
[b]What’s the differences between

#pragma pack(1)
//…

and

What’s the differences between

#pragma pack(1)
//structure

and

#pragma pack(push, 1)
//structure
#pragma pack(pop)[/b]

The latter version will revert to the previously used pack method (=nice), whereas the former will leave it at 1 (=not so nice), which is not what subsequent code may expect.

HTH

Jean-Marc

Understood.