我的代码有一个结构类型定义如下:
typedef struct
{
Structure_2 a[4];
UCHAR b;
UCHAR c;
}Structure_1;
其中 Structure_2 的定义如下:
typedef struct
{
ULONG x;
USHORT y;
UCHAR z;
}Structure_2;
代码中还有两个函数。第一个(名为 setter)声明了一个“Structure_1”类型的结构并用数据填充它:
void setter (void)
{
Structure_1 data_to_send ;
data_to_send.a[0].x = 0x12345678;
data_to_send.a[0].y = 0x1234;
data_to_send.a[0].z = 0x12;
data_to_send.a[1].x = 0x12345678;
data_to_send.a[1].y = 0x1234;
data_to_send.a[1].z = 0x12;
data_to_send.a[2].x = 0x12345678;
data_to_send.a[2].y = 0x1234;
data_to_send.a[2].z = 0x12;
data_to_send.a[3].x = 0x12345678;
data_to_send.a[3].y = 0xAABB;
data_to_send.a[3].z = 0x12;
data_to_send.b =0;
data_to_send.c = 0;
getter(&data_to_send);
}
编译器将 data_to_send 保存在内存中,如下所示:
第二个命名为 getter:
void getter (Structure_1 * ptr_to_data)
{
UCHAR R_1 = ptr_to_data -> b;
UCHAR R_2 = ptr_to_data -> c;
/* The remaining bytes are received */
}
我希望 R_1 的值为“00”,而 R_2 的值为“00”。
但是发生的是编译器会像这样翻译以下两行:
/* Get the data at the address ptr_to_data -> b,
which equals the start address of structure + 28 which contains the
value “AA”, and hence R_1 will have “AA” */
UCHAR R_1 = ptr_to_data -> b;
/* Get the data at the address ptr_to_data -> c,
which equals the start *address of structure + 29 which contains the
value “BB”, and hence R_2 will *have “BB” */
UCHAR R_2 = ptr_to_data -> c;
编译器在将结构保存在堆栈中的同时添加了填充 b/yte,但是当它开始读取它时,它忘记了它做了什么(并在读取中包含了填充字节)。
我如何通知编译器在读取结构元素时应该跳过填充字节?
我不想解决这个问题,我很想知道为什么编译器会这样?
我的编译器是 GreenHills,我的目标是 32 位