数组的大小加倍,如果一个结构定义了它的uint16_t单词和uint8_t有字节 [英] Array doubles in size if a struct defines both its uint16_t words and uint8_t bytes

查看:1219
本文介绍了数组的大小加倍,如果一个结构定义了它的uint16_t单词和uint8_t有字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的每一个,它的元素可以是uint16_t或一对uint8_t有阵列

I have an array each of whose elements could be either uint16_t or a pair of uint8_t.

及其元素被定义为一个uint16_t的联合和2 uint8_t有一个子阵列

Its elements are defined as a union of a uint16_t and a sub-array of 2 uint8_t.

不幸的是,编译器(微芯片XC16)分配两倍的内存,因为它应该为阵。

Unfortunately, the compiler (MicroChip XC16) allocates twice as much memory as it should for the array.

typedef union {
   uint16_t u16;   // As uint16_t
   uint8_t  u8[2]; // As uint8_t
} my_array_t;

my_array_t my_array[1]; // 1 word array, for testing

my_array[0].u8[0] = 1;
my_array[0].u8[1] = 2;
uint8_t byte_0 = my_array[0].u8[0]; // Gets 0x01
uint8_t byte_1 = my_array[0].u8[1]; // Gets 0x02
uint16_t byte_0 = my_array[0].u16; // Gets 0x0201

编译器分配4个字节,而不是2个字节,它应。

The compiler allocates 4 bytes instead of 2 bytes as it should.

解决方法:如果我改变结构为:

Workaround: if I change the struct to:

typedef union {
   uint16_t u16;   // As uint16_t
   uint8_t  u8[1];   // As uint8_t
} my_array_t;

编译器分配2个字节,因为它应该,但随后这是不正确的:

The compiler allocates 2 bytes as it should, but then this is incorrect:

my_array[0].u8[1] = 2;

但它仍然有效:

uint8_t byte_1 = my_array[0].u8[1]; // Gets 0x02

(除了不便,即调试器不显示其值)。

(except for the inconvenience that the debugger doesn't show its value).

问:我应该住的解决办法,还是应该用更好的解决办法。

Question: should I live with the workaround, or should I use a better solution?

请参阅一<一href=\"http://stackoverflow.com/questions/26936057/proper-way-to-access-array-members-as-a-different-type\">$p$pvious这个,其中有人提出上述方案的讨论。

Please refer to a previous discussion on this, where the above solution was suggested.

编辑。

每EOF的建议(见下文),我检查的sizeof。

Per EOF's suggestion (below), I checked sizeof.

解决方法之前:

sizeof(my_array_t) // Is 4
sizeof(my_array[0]) // Is 4
sizeof(my_array[0].u8) // Is 2

在解决方法:

sizeof(my_array_t) // Is 2
sizeof(my_array[0]) // Is 2
sizeof(my_array[0].u8) // Is 2

这将表明,这是一个编译器错误。

That would indicate that it's a compiler bug.

推荐答案

而不是2个字节数组,使用2个字节的结构:

Instead of an array of 2 bytes, use a structure of 2 bytes:

// Two bytes in a 16-bit word
typedef struct{
    uint8_t     lsb;    // As uint8_t, LSB
    uint8_t     msb;    // As uint8_t. MSB
} two_bytes_t;

typedef union {
   uint16_t u16;   // As uint16_t
   two_bytes_t  u8x2; // As 2 each of uint8_t
} my_array_t;


my_array_t my_array[1]; // 1 word array, for testing

my_array[0].u8x2.msb = 1;
my_array[0].u8x2.lsb = 2;

的XC16编译器正确地仅分配2个字节用于每个元素,并且调试器正确地显示各个字节。

The XC16 compiler correctly allocates only 2 bytes for each element, and the debugger correctly shows the individual bytes.

这篇关于数组的大小加倍,如果一个结构定义了它的uint16_t单词和uint8_t有字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆