c 如何从另一个结构变量初始化结构数组成员

标签 c gcc

示例代码:

#define ARR_SZ 1000

struct a
{
        int arr[ARR_SZ];
};

const struct a b = {
        .arr = { 1, 2, 3},
};

struct a c = {
        .arr = b.arr,
};

如何在不使用 memcpy 的情况下将 b.arr 初始化为 a.arr。上面的代码编译时出错:

test.c:14:9: warning: initialization of ‘int’ from ‘const int *’ makes integer from pointer without a cast [-Wint-conversion]
   14 |  .arr = b.arr,
      |         ^
test.c:14:9: note: (near initialization for ‘c.arr[0]’)
test.c:14:9: error: initializer element is not computable at load time
test.c:14:9: note: (near initialization for ‘c.arr[0]’)

如果 ARR_SZ 是一个固定的小值,例如3、我们可以为每个成员(member)写信。

struct a d = {
        .arr = { b.arr[0], b.arr[1], b.arr[2] },
};

但是如果ARR_SZ很大,我们如何初始化它。

我找到了一个解决方案,添加一个结构包装器

#define ARR_SZ 1000

struct a
{
        struct {
                int arr[ARR_SZ];
        } dummy;
};

const struct a b = {
        .dummy.arr = { 1, 2, 3},
};

struct a c = {
        .dummy = b.dummy,
};

最佳答案

不能用另一个数组来初始化一个数组。但是,您可以使用 b 初始化对象 c:

struct a c = b;

如果您需要仅从 b 初始化数组,而从其他地方初始化其他成员,请将数组放入其自己的 struct 中并使用该类型在所有应该有这个数组的struct中:

struct arr_holder {
    int arr[ARR_SZ];
};

struct a {
    struct arr_holder ah;
};

const struct a b = {
    .ah = {{1, 2, 3}}
};

struct a c = {.ah = b.ah };

如果只有struct a需要这个int[ARR_SZ],你可以内联定义它:

struct a {
    struct {
        int arr[ARR_SZ];
    } ah;
};

关于c 如何从另一个结构变量初始化结构数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76499143/

相关文章:

gcc - "#pragma pack"和 "__attribute__((aligned))"有什么区别

gcc - arm拇指模式代码生成——gcc arm linux编译器

c - ANSI C - 变量范围

c - 如何在 vim 中对齐多个赋值

c - Vim 自动缩进 : Align an array initialization which extends over multiple lines

python - 此系统上未安装 c++ 编译器

c - 尝试通过创建模拟串行设备来测试 C 代码

c - 如何释放函数外部 malloc() 使用的内存?

c++11 - g++ 5.4.0 - 无法使用 C++14 标准

c - MinGW GCC - 未定义对 `atexit' 的引用