C指向数组的联合指针

时间:2018-07-24 09:54:38

标签: c arrays pointers unions

我有一个无符号的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]);

尽管这可行,但我收到警告:从不兼容的指针类型分配

有更好的方法吗?我无法更改数组,但是可以随意更改结构,联合或指向数组的指针。

2 个答案:

答案 0 :(得分:1)

  1. Change unsigned to uint16_t

why? - test the difference: 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;
}

The most correct way is to declare the table as table of structs.

If not :

If you want too work on the bitfields you do not actually have to declare the pointer.

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

and it is almost portable and safe way

you can also cast it explicitly

答案 1 :(得分:0)

The warning says that uint16_t* is not compatible with SupplyStatus_t*. If you want to get rid of this warning, cast it to SupplyStatus_t*:

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

I also would put the union and struct together:

typedef union
{
  struct
  {
    unsigned statusCode : 4;
    unsigned errorCode : 4;
    unsigned outputEnabled : 1;
    unsigned currentClip :1;
    unsigned unused : 6;
  } s;
  uint16_t value;
} SupplyStatus_t;