C 具有 uint8 数组奇怪行为的结构

C Struct with uint8 array weird behavior

本文关键字:结构 具有 uint8 数组      更新时间:2023-10-16

>我对以下 C 结构有问题:

typedef struct AnchorPixel{
    int32 X;
    int32 Y;
    uint8 CH[5];
} AnchorPixel;

实际上,我对里面的CH数组有问题。我只是无法操作CH数组。例如,以下程序

AnchorPixel a;
a.CH[2] = 5;
cout << a.CH[2];

给出输出:

如果我将 CH 类型从 uint8 更改为 int32,问题就会消失。这有效:

typedef struct AnchorPixel{
        int32 X;
        int32 Y;
        int32 CH[5]; 
    } AnchorPixel;

有什么想法吗?

似乎uint8被类型化为unsigned char,我们可以在 coliru 上看到uint8_t是这种情况。cstdint 标头包含 stdint.h 并且确实有一个 typedef uint8_t unsigned char

typedef unsigned char       uint8_t;

您看到的输出与将a.CH[2]视为char类型的cout一致,