示例代码:
#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/