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

implementing node using typedef vs not using 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? 任何启发将不胜感激。

对于下面的内容,请检查下一个结构节点是否必须是结构node_int。 请编译并解决错误,您可能会想到它。

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

将指针隐藏在诸如 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;
}