gpt4 book ai didi

c - 结构体元素的初始化

转载 作者:行者123 更新时间:2023-11-30 20:20:32 30 4
gpt4 key购买 nike

为什么不使用以下代码将结构体指针初始化为 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;
}

输出

11110

这是关于指针初始化语法的问题吗?

最佳答案

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 *右,*左,*父级; },声明了一个名为 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 没有类型的默认值。您总是必须初始化它们。使用结构时,这通常意味着编写 newdestroy 函数,以便一致地进行初始化和清理。

// 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;
}

请注意,我没有使用calloccalloc 用零填充内存,但是 the machine's representation of a null pointer is not necessarily zero 。使用 NULL0 是安全的,编译器可以根据上下文进行翻译,但 calloc 不知道你要做什么与内存归零。这是一个相对较小的可移植性问题,但如今对于嵌入式系统来说可能是一个更大的问题。

关于c - 结构体元素的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46006730/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com