04-06-2011 03:00 AM
Hi,
in CVI2010 the sizeof-operator returns a wrong size of a struct, if it contains 4 bytes and other spaces. I suppose the adresses in the struct are also not like a c-programmer thinks. First a minimalistic code-example:
typedef struct
{
char oneByte;
long fourByte;
} TestStruct;
void main( )
{
int size;
TestStruct tmpVar;
size = sizeof( TestStruct );
// here is size=8 instead of 5
}
Since the last years and the last cvi-versions i had ever compiled with the Borland-compiler, that returns the correct size. Because in CVI 2010 the Borland-compiler is not included, i'm trying to use the standard build-In compiler. In my opinion the compiler seems to optimize the code in a way, my project can't work with.
Because i'm reading the struct direct out of binary files i'm searching for a, not code based, solution.
Is it possible to deactivate the relevant optimization?
Thanks for your help and answer.
Markus
Solved! Go to Solution.
04-06-2011 05:01 AM
The compiler can have different alignments for struct fields: a usual behaviour is to have them aligned on a 4-byte boundary, that is every field starts on a multiple of 4 bytes from the beginning of the struct in memory. This appears to be the behaviour of the compiler you are using at the moment, which returns 8 as the size of the struct having aligned the fields.
Struct alignment can be modified with an appropriate #pragma preprocessor instruction: adding #pragma pack (1); in your code instructs the compiler to pack structure fields without padding; after this instruction sizeof will return the 5-bytes dimension you are expecting.
04-06-2011 05:13 AM
04-06-2011 05:17 AM
You're welcome!
Just to add some informations, tghe following knowledgebase entry can be of some help. I suggest you take a look at the Programmer's Reference manual sections mentioned in it too:
Which Pragmas Are Supported in LabWindows/CVI?