[英]C union pointer to array
我有一个无符号的16位整数数组:
static uint16_t dataArray[7];
数组的第7个元素的位表示某种状态。 我想以一种简单的方式获取并设置此状态的值,而不必进行移位,也不必每次状态更改时都将新值复制到数组中。 所以我创建了一个带有结构和指针的联合:
typedef struct {
unsigned statusCode : 4;
unsigned errorCode : 4;
unsigned outputEnabled : 1;
unsigned currentClip : 1;
unsigned : 6;
} SupplyStruct_t;
typedef union {
SupplyStruct_t s;
uint16_t value;
} SupplyStatus_t;
static SupplyStatus_t * status;
我的初始化例程希望状态指针指向数组的第7个元素,因此我尝试:
status = &(dataArray[6]);
尽管这可行,但我得到警告: 来自不兼容指针类型的赋值
有一个更好的方法吗? 我无法更改数组,但是可以随意更改结构,联合或指向数组的指针。
unsigned
更改为uint16_t
为什么? -测试差异: https : //ideone.com/uHLzpV
#include <stdio.h>
#include <stdint.h>
typedef struct {
uint16_t statusCode : 4;
unsigned errorCode : 4;
unsigned outputEnabled : 1;
unsigned currentClip : 1;
unsigned : 6;
} SupplyStruct_t;
typedef struct {
uint16_t statusCode : 4;
uint16_t errorCode : 4;
uint16_t outputEnabled : 1;
uint16_t currentClip : 1;
uint16_t : 6;
} SupplyStruct_t1;
typedef union {
SupplyStruct_t s;
uint16_t value;
} SupplyStatus_t;
typedef union {
SupplyStruct_t1 s;
uint16_t value;
} SupplyStatus_t1;
int main(void) {
printf("%zu %zu\n", sizeof(SupplyStatus_t), sizeof(SupplyStatus_t1));
return 0;
}
最正确的方法是将表声明为结构表。
如果不 :
如果您也想在位域上工作,则实际上不必声明指针。
static SupplyStatus_t status;
status.value = dataArray[6];
这几乎是便携式和安全的方式
您也可以显式投射
警告说uint16_t *与SupplyStatus_t *不兼容。 如果要消除此警告,请将其强制转换为SupplyStatus_t *:
status = (SupplyStatus_t*)&(dataArray[6]);
我也将工会和结构放在一起:
typedef union
{
struct
{
unsigned statusCode : 4;
unsigned errorCode : 4;
unsigned outputEnabled : 1;
unsigned currentClip :1;
unsigned unused : 6;
} s;
uint16_t value;
} SupplyStatus_t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.