c++ - 初始化 struct 类型的常量数组

标签 c++ data-structures

我无法初始化自定义类型的常量数组。代码如下:

union chk {
    struct{
        int a : 4;
        int b : 12;
    }stNative;
    int nVal;
};

const chk obj[2] = {0x1234, 0x6789};

int main() {
    
    cout << obj[0].nVal<<endl;
}

执行上述代码时,我得到一些随机值。 我无法理解发生这种情况的原因以及如何解决它。 上述代码的O/P为:30868

最佳答案

声明中的初始化将值分配给第一个 union 成员stNative,这是一个具有两个值的结构。您已为第一个结构成员 a 提供了溢出的值。这个小更新将初始化两个结构成员。

#include <iostream>
using namespace std;

union chk {
    struct{
        int a : 4;
        int b : 12;
    }stNative;
    int nVal;
};

const chk obj[2] = {{0x1, 0x234}, {0x6, 0x789}};

int main() {
    // Undefined behaviour bellow while reading nVal
    cout << std::hex << obj[0].nVal<<endl;
}
// Output: 2341

C++ 中不允许类型双关。如果初始化 union 成员stNative,则只能读取它,不允许读取nVal。使用std::bit_cast或用于类型双关的memcpy。

关于c++ - 初始化 struct 类型的常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73246125/

相关文章:

c++ - 从正则表达式构建元组

C++ 序列化/反序列化 std::map<int,int> 从/到文件

c++ - 运行时错误 : Program skipping prompt for second and third names

c++ - 反转指向数据成员的指针

java - 在另一个字符串中查找字符串的 Anagrams 的最佳算法

c++ - this_thread::sleep_for 影响其他线程

判断一个图是否为树的算法

c# - 字典可以按不同的键排序吗?

c - C语言中栈的push方法的实现

c - 为什么这里会出现无限循环呢? (链表打印)