Domanda

I have this sample code which I decorated with pack to make sure that its size if 5 byte (4 for int and 1 for char).

but it print out that the size of struct is 8 byte.

#pragma pack push
#pragma pack 1
struct mystruct
{
    int x;
    char y;
};
#pragma pack pop

//static_assert(sizeof(mystruct) == 5, "Size of mystruct should be 5 byte.");

int _tmain(int argc, _TCHAR* argv[])
{
    int x=sizeof(mystruct);
    printf("size of struct is %d\n",x);
    return 0;
}

Why te pck is not working?

How can make sure that size of struct is always 5.

È stato utile?

Soluzione

Your pragma syntax is wrong.

Try this:

#pragma pack(push,1)
...
#pragma pack(pop)

Demo.

Altri suggerimenti

I believe the compiler is permitted to ignore the pack pragma; perhaps it can be overridden with compiler switches.

The compiler can always ignore your attempts to stop packing. This, in some ways, is a good thing, as the packing allows a higher level of efficiency... Think of an array, when you access element 1, it is efficiently traversed to as the distance, in terms of memory, between the elements is uniform. This is also performed with structures in order to ensure efficiency is maintained.

I direct you to this stack overflow Disable structure padding in C without using pragma

Strange- I have structs in a 3rd party program that are packed on 1-byte boundaries and they do work as expected (though not liked!).

If the compiler is ignoring your pragmas, try setting the alignment compiler options as well - C/C++ | Code Generation | Struct Member Alignment to 1.

If the compiler is doing an "I know best" optimisation, perhaps putting the char first would stop it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top