struct元素的初始化

时间:2017-09-01 19:19:34

标签: c pointers struct

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

是否有关于指针初始化语法的问题?

2 个答案:

答案 0 :(得分:1)

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}。< / p>

除了类型定义,这基本上是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不知道你将如何处理内存的归零。这是一个相对较小的可移植性问题,如今对于嵌入式系统来说可能更成问题。

答案 1 :(得分:0)

Structure是一种数据类型,您不会为数据类型提供默认值。你正在做的就是给一个默认值为3的int。你想要的是给你的结构的一个实例一个默认值,但这在C中是不可能的。

你可以有一个功能来帮助你:



    void init_struct(node* nd) {
      if (nd != NULL) {
        nd->val = 0;
        nd->parent = nd->right = nd->left = NULL;
      }
    }


相关问题