You can use pragma to change change byte alignment.
for ex
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
} s;
Size of this structure is of 11 Bytes. but due to default
byte alignment(8 byte) which is different for different
compilers. The size of structure would be 16 Bytes.
In order to change the alignment, we will have to do
something like this.
#pragma pack(1)
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
//unsigned char b;
} s;
#pragma pack()
This will change the byte alignment to 1 Byte. and thus size of structure will be exactly 11 bytes
#include
int x;
int x=10;
#pragma pack(1)
struct testpad
{
int i;
unsigned char c;
} pad;
#pragma pack()
struct test
{
int i;
unsigned char c;
} s;
int main()
{
printf("X:%d WITHOUT PAD:%d, WITH PAD:%d\r\n",x,sizeof(s), sizeof(pad) );
return 0;
}
O/p: X:10 WITHOUT PAD:8, WITH PAD:5
for ex
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
} s;
Size of this structure is of 11 Bytes. but due to default
byte alignment(8 byte) which is different for different
compilers. The size of structure would be 16 Bytes.
In order to change the alignment, we will have to do
something like this.
#pragma pack(1)
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
//unsigned char b;
} s;
#pragma pack()
This will change the byte alignment to 1 Byte. and thus size of structure will be exactly 11 bytes
#include
int x;
int x=10;
#pragma pack(1)
struct testpad
{
int i;
unsigned char c;
} pad;
#pragma pack()
struct test
{
int i;
unsigned char c;
} s;
int main()
{
printf("X:%d WITHOUT PAD:%d, WITH PAD:%d\r\n",x,sizeof(s), sizeof(pad) );
return 0;
}
O/p: X:10 WITHOUT PAD:8, WITH PAD:5
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.