为什么不使用以下代码将结构指针初始化为 NULL
代码
#include <stdio.h>
#include <stdlib.h>
struct list_el
{
int val;
struct list_el * right, * left, *parent;
}item_default={0,NULL,NULL,NULL}; //Default values
typedef struct list_el node;
int main(int argc, char const *argv[])
{
node * new_node = (node*) malloc (sizeof(node));
(new_node == NULL) ? printf("0\n") : printf("1\n");
(new_node->parent == NULL) ? printf("0\n") : printf("1\n");
(new_node->right == NULL) ? printf("0\n") : printf("1\n");
(new_node->left == NULL) ? printf("0\n") : printf("1\n");
(new_node->val == 0) ? printf("0\n") : printf("1\n");
return 0;
}
输出
1 1 1 1 0
是关于指针初始化语法的一些问题吗?
struct list_el
{
int val;
struct list_el * right, * left, *parent;
}item_default={0,NULL,NULL,NULL}; //Default values
这不会像你认为的那样做。你基本上写了...
typename typedefinition variable = initial_value;
您已经声明了类型struct list_el
,将其定义为{ int val; struct list_el * right, * left, *parent; }
,声明了一个名为 的该类型的新变量item_default
,并为其分配了值{0,NULL,NULL,NULL}
。
除了类型定义,这基本上是int foo = 0
.
我们可以通过打印item_default
.
int main(int argc, char const *argv[])
{
printf("%d\n", item_default.val);
printf("%p\n", item_default.right);
printf("%p\n", item_default.left);
printf("%p\n", item_default.parent);
return 0;
}
这些将是 0、0x0(即NULL
)、0x0、0x0。
不幸的是,C 没有类型的默认值。您必须始终初始化它们。使用结构时,这通常意味着编写new
和destroy
函数,以便初始化和清理始终如一地发生。
// Declare the type and typedef in one go.
// I've changed the name from node to Node_t to avoid clashing
// with variable names.
typedef struct node
{
int val;
struct node *right, *left, *parent;
} Node_t;
// Any functions for working with the struct should be prefixed
// with the struct's name for clarity.
Node_t *Node_new() {
Node_t *node = malloc(sizeof(Node_t));
node->val = 0;
node->right = NULL;
node->left = NULL;
node->parent = NULL;
return node;
}
int main() {
Node_t *node = Node_new();
printf("%d\n", node->val);
printf("%p\n", node->right);
// and so on
return 0;
}
请注意,我没有使用calloc
. calloc
用零填充内存,但机器对空指针的表示不一定为零。使用NULL
和0
是安全的,编译器可以从上下文进行翻译,但calloc
不知道您将如何处理其归零的内存。这是一个相对较小的可移植性问题,如今对于嵌入式系统来说可能更像是一个问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句