我选择了数组初始化方法:
#include <stdarg.h>
void int_array_init(int *a, const int ct, ...) {
va_list args;
va_start(args, ct);
for(int i = 0; i < ct; ++i) {
a[i] = va_arg(args, int);
}
va_end(args);
}
称为,
const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);
C99 数组初始化如下所示:
const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
在configure.ac
文件中:
AC_PROG_CC_C99
我在我的开发机上编译器完全正常运行。但是服务器上的编译器报错:
error: variable-sized object may not be initialized
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
并且
warning: excess elements in array initializer
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
对于每个元素
例如,它不会抱怨:
int expected[] = { 1, 2, 3, 4, 5 }
我喜欢对大小的检查,并且varargs支持比数组初始化程序的支持更加健壮。
在https://github.com/wbreeze/davenport/pull/15/files中找到带有示例代码的PR。
关于@paxdiablo的https://dev59.com/pnA65IYBdhLWcg3w-jym#3535455,我很喜欢,但是感到不安,因为初始化指针移动的次数与分配给数组的元素数量同步。最坏的情况是初始化指针超过了分配的长度。因此,PR中的差异包含如下内容:
int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);
int_array_init
方法会安全地分配垃圾值,如果参数的数量少于节点数(node_ct),将会执行这个操作。垃圾赋值应该更容易被发现和调试。
memcpy
复制另一个结构体之外,没有简单的方法来批量分配成员。我经常发现自己希望有这个功能。 - bta