初始化指向 NULL 的指针数组
Initializing an array of pointers to NULL
我得到了一个为树数据结构定义节点的结构:
struct Node {
int data;
struct Node *children[10];
}
鉴于 children
不是动态数组,我想将 children
的每个指针初始化为 NULL,但以下内容不起作用:
struct Node {
int data;
struct Node *children[10]={NULL};
}
有什么解决方法吗?
struct Node {
int data;
struct Node *children[10];
} a = {.children = {0}};
a
是一个 struct Node
对象,children
成员的所有元素都初始化为空指针。
您无法初始化 struct
描述中的数据,因为尚未分配内存。
让我们看看您将看到的两种分配方式:
堆栈
struct Node my_node = {
0,
{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
};
或者,因为未列出的值将默认为 0
...
struct Node my_node = {};
堆:
在这里,唯一的选择是清除内存。我们可以使用 calloc()
来执行此操作,因为它 returns 的内存已清零。
struct Node *my_node = calloc(1, sizeof(*my_node));
或者,我们可以明确地使用 memset()
:
struct Node *my_node = malloc(sizeof(*my_node));
memset(my_node, 0, sizeof(*my_node));
备注:
我通常假设 NULL == 0
。这不一定是真的。如果您想阅读更多关于这些(大部分)历史系统的信息:When was the NULL macro not 0?
如果您在其中一个系统上,或者您担心您的代码在这些平台上工作,那么我建议使用我描述的第一种方法(也是最明确的)方法。它将在所有 平台上运行。
这个
struct *Node children[10];
错了。我什至不会编译。应该是
struct Node *children[10];
要将成员 children
的所有元素初始化为 NULL
,您可以使用指定的初始化程序。
struct Node {
int data;
struct Node *children[10];
} node = {.children = {NULL}};
我得到了一个为树数据结构定义节点的结构:
struct Node {
int data;
struct Node *children[10];
}
鉴于 children
不是动态数组,我想将 children
的每个指针初始化为 NULL,但以下内容不起作用:
struct Node {
int data;
struct Node *children[10]={NULL};
}
有什么解决方法吗?
struct Node {
int data;
struct Node *children[10];
} a = {.children = {0}};
a
是一个 struct Node
对象,children
成员的所有元素都初始化为空指针。
您无法初始化 struct
描述中的数据,因为尚未分配内存。
让我们看看您将看到的两种分配方式:
堆栈
struct Node my_node = {
0,
{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
};
或者,因为未列出的值将默认为 0
...
struct Node my_node = {};
堆:
在这里,唯一的选择是清除内存。我们可以使用 calloc()
来执行此操作,因为它 returns 的内存已清零。
struct Node *my_node = calloc(1, sizeof(*my_node));
或者,我们可以明确地使用 memset()
:
struct Node *my_node = malloc(sizeof(*my_node));
memset(my_node, 0, sizeof(*my_node));
备注:
我通常假设 NULL == 0
。这不一定是真的。如果您想阅读更多关于这些(大部分)历史系统的信息:When was the NULL macro not 0?
如果您在其中一个系统上,或者您担心您的代码在这些平台上工作,那么我建议使用我描述的第一种方法(也是最明确的)方法。它将在所有 平台上运行。
这个
struct *Node children[10];
错了。我什至不会编译。应该是
struct Node *children[10];
要将成员 children
的所有元素初始化为 NULL
,您可以使用指定的初始化程序。
struct Node {
int data;
struct Node *children[10];
} node = {.children = {NULL}};