c++ - 如何在不单独执行每个元素的情况下初始化结构内的数组? (C++)

标签 c++ arrays struct

我的问题在代码中,但基本上我想知道如何/是否可以执行这两行注释掉的代码?我知道我可以在构造函数中完成,但我不想这样做!

struct foo
{
    int b[4];
} boo;

//boo.b[] = {7, 6, 5, 4}; // <- why doesn't this work? (syntax error : ']')
//boo.b = {7, 6, 5, 4}; // <- or else this? (syntax error : '{')

boo.b[0] = 7; // <- doing it this way is annoying
boo.b[1] = 6; // :
boo.b[2] = 5; // :
boo.b[3] = 4; // <- doing it this way is annoying

boo.b[4] = 3; // <- why does this work!

(使用:C++、Visual Studio 2005。)

最佳答案

只能在定义中使用初始化:

struct foo
{
    int b[4];
};
foo boo = { 7, 6, 5, 4 };

关于最后一个问题:“为什么 boo.b[4] = 3 有效?”答案是它是未定义的行为,并且 UB 允许相当多的不同情况。编译器和运行时环境都不必对其进行诊断,在许多情况下,结果将覆盖内存中的下一个元素。可以使用以下代码进行测试:

// Test
foo boo;
int x = 0;
boo.b[4] = 5;
std::cout << x << std::endl;

注意:这是未定义的行为,因此无论测试结果如何,它都是不正确的,不能假定为可重复的测试。

关于c++ - 如何在不单独执行每个元素的情况下初始化结构内的数组? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835393/

相关文章:

c++ - Zenlib 错误 : undefined reference to Open function call which uses typedef

c++ - 可移植比较和交换(原子操作)C/C++ 库?

c++ - 使用 CMake 生成的系统在构建时运行 Google 测试

arrays - Hive JSON数据 explode 选项不 explode 数组

c++ - 以一定概率运行代码

java - 无法将 double 型格式化为在小数点分隔符后打印 2 位数字

matlab - 一次分配多个字段的巧妙方法?

带指针声明的 C 动态结构赋值

C - 将值插入到结构中

c++ - 警告: "when type is in parentheses, array cannot have dynamic size"?的原因是什么