LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

CVI2010 sizeof-operator returns a wrong size of a struct

Solved!
Go to solution

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

 

 

0 Kudos
Message 1 of 4
(3,792 Views)
Solution
Accepted by topic author MarkusHil

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.

 



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
Message 2 of 4
(3,783 Views)
Thanks a lot. That's it.
0 Kudos
Message 3 of 4
(3,779 Views)

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?



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 4 of 4
(3,777 Views)