LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Size of structure dependant of elements order

Solved!
Go to solution

Hello,

I am using a structure in a LabWindows application and I am having problems with its size. Its size seems to depend on the order of the elements.

Here is a program that pinpoints the problem:

 

#include <ansi_c.h>

 

typedef struct{
 unsigned short int try;
 float try2;
 double try3;
} STRUCT1;

 

typedef struct{
 float try2;  
 double try3;
 unsigned short int try;
} STRUCT2;
 

int main (int argc, char *argv[])
{
 int number=0;

 printf("The memory size of STRUCT1 is:%d",sizeof(STRUCT1));
 printf("\nThe memory size of STRUCT2 is:%d",sizeof(STRUCT2));
 scanf("%d",&number);
 
 return 0;
}

 

If I run this program using LabWindows 8.5, I will get the following:

 The memory size of STRUCT1 is: 16

 The memory size of STRUCT2 is: 24

even though the structures are identical.

 

The problem is that I am trying to access the memory location of the structure byte by byte to do a parity check but the sizeof

doesn't return the actual size of my structure and so I get back random data. Has anybody encountered the same problem?

Thanks

Cyril

0 Kudos
Message 1 of 3
(3,469 Views)
Solution
Accepted by topic author gfdsg

There is a discussion here which should explain what is happening.

 

JR

0 Kudos
Message 2 of 3
(3,466 Views)

Thank you very much, it worked perfectly. To all, the solution is to add  #pragma pack(4) as shown below.

For any further information, look for "structure packing" in the LabWindows help .

 

Cyril

 

#include <ansi_c.h>
#pragma pack(4)
typedef struct{
 unsigned short int try;
 float try2;
 double try3;
} STRUCT1;

typedef struct{
 float try2;  
 double try3;
 unsigned short int try;
} STRUCT2;
#pragma pack() 

int main (int argc, char *argv[])
{
 int number=0;

 printf("The memory size of STRUCT1 is:%d",sizeof(STRUCT1));
 printf("\nThe memory size of STRUCT2 is:%d",sizeof(STRUCT2));
 scanf("%d",&number);
 
 return 0;
}

0 Kudos
Message 3 of 3
(3,463 Views)