12-11-2008 05:04 AM
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
Solved! Go to Solution.
12-11-2008 05:21 AM
12-11-2008 06:07 AM
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;
}