我有一个单向链表类型,长这样:
struct point { int x, y; };
struct point_list {
struct point value;
const struct point_list *next;
};
我希望对这些列表之一进行静态初始化,可能会有几十个条目。 我想每行写一个项目,并保持一致的缩进,以便轻松编辑该列表。 到目前为止,我能想到的最好方法是这样的:
const struct point_list *const my_list =
&(const struct point_list) { .value = { 1, 2 }, .next =
&(const struct point_list) { .value = { 3, 4 }, .next =
&(const struct point_list) { .value = { 5, 6 }, .next =
NULL
}}};
但是这种方法存在以下缺点:
- 当我添加或删除项目时,需要更新最后一行的闭合括号数量。
- 可能很难说服代码格式化程序保持这种风格。
是否有更好的方法呢?
如果我们有递归宏,也许可以尝试以下方式:
const struct point_list *const my_list = POINT_LIST(
((struct point) { 1, 2 }),
((struct point) { 3, 4 }),
((struct point) { 5, 6 }),
);
如果我们可以在编译时运行代码,也许可以像这样工作:
#define array_length(X) (sizeof(X) / sizeof(X[0]))
constexpr const struct point_list *array_to_list(size_t length, struct point *values) { ... }
const struct point my_array[] = {
{ 1, 2 },
{ 3, 4 },
{ 5, 6 },
};
const struct point_list *const my_list = array_to_list(array_length(my_array), my_array);
const struct point *next;
应该改为const struct point_list *next;
吗? - Eric Postpischilconst struct point *next;
是个错误。(那不会是一个链表!)我已经编辑了那一行。 - dpercy