使用typedef与不使用typedef实现节点

时间:2018-11-01 07:17:57

标签: c malloc nodes typedef

我不确定我是否了解typedef的概念...说有两种不同的实现节点的方法:一种使用typedef,另一种不使用typedef。 例如:

有一个这样实现的节点:名为 node1.c 的文件如下所示:

struct node_int {
  int value;
  node next;
};
void init_node(node *n, int value) {
    node new_node = (node)malloc(sizeof(struct node_int));
    //some code for initializing
}

,并在 node1.h 中如下所示:

struct node_int;
typedef struct node_int *node;

有一个这样实现的节点:其中名为 node2.c 的文件如下所示:

struct node_int {
    int value;
    struct node *next;
};

void init_node(node_int **n, int value) {
    struct node_int* new_node = (struct node_int*)malloc(sizeof(struct node_int));
    //some code for initializing
}

,并在 node2.h 中如下所示:

struct node_int;

这两个实现等效吗?是否在每种情况下都正确使用了malloc? 任何启发将不胜感激。

2 个答案:

答案 0 :(得分:3)

在诸如typedef struct node_int *node;之类的typedef后面隐藏指针容易出错,并且使许多程序员感到困惑。您应该避免这样做。您可以为struct标签和typedef使用相同的标识符:

typedef struct node node;

struct node {
    int value;
    node *next;
};

node *init_node(int value) {
    node *np = malloc(sizeof(*np));
    if (np != NULL) {
        np->value = value;
        np->next = NULL;
    }
    return np;
}

答案 1 :(得分:0)

对于以下情况,请检查下一个结构节点是否必须为struct node_int。 请编译并解决错误,您可能会对此有所了解。

struct node_int{ int value; struct node *next; }

相关问题