C 指向数组的联合指针

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]);

尽管这有效,但我收到警告:来自不兼容指针类型的赋值

有更好的方法吗?我不能更改数组,但我可以自由更改结构、联合或指向数组的指针。

警告说 uint16_t* 与 SupplyStatus_t* 不兼容。 如果您想摆脱此警告,请将其转换为 SupplyStatus_t*:

status = (SupplyStatus_t*)&(dataArray[6]);

我也会把 union 和 struct 放在一起:

typedef union
{
  struct
  {
    unsigned statusCode : 4;
    unsigned errorCode : 4;
    unsigned outputEnabled : 1;
    unsigned currentClip :1;
    unsigned unused : 6;
  } s;
  uint16_t value;
} SupplyStatus_t;
  1. 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;
}

最正确的方法是将 table 声明为结构体的 table。

如果没有:

如果您还想在位域上工作,实际上不必声明指针。

static SupplyStatus_t status;
status.value = dataArray[6];

这几乎是table和安全的方式

你也可以显式转换它