结构指针前向声明?

Structure pointer forward declaration?

我是 c 编程和创建链表数据结构的新手,我的老师给了我一些看起来有点混乱的代码:

typedef struct node *ptr;
ptr start,current;
typedef struct node{
    int value;
    ptr next;
};

这段代码工作正常,使用其他函数我可以创建一个链表,我的困惑是,当我像这样更改代码时:

node *start;
node *current;
typedef struct node{
    int value;
    node *next;
};

它不起作用。这段代码有什么问题为什么我不能再转发声明节点指针了。

你在第二种情况下所做的不是前向声明。它试图在不定义类型的情况下使用类型 (node)。

第一种情况也不行。它给出以下警告:

warning: useless storage class specifier in empty declaration

那是因为您没有为 struct node 分配类型别名。你必须这样做:

typedef struct node{
    int value;
    ptr next;
} node;

现在,您可以使用 node 代替 struct node

typedef struct node *ptr;
ptr start,current;
typedef struct node{
    int value;
    ptr next;
};

struct 本身的 typedef 不会以这种方式工作,我猜你在最后缺少一个 node(它缺少新定义类型的标识符)。

在这一点上,我会告诉你的老师请不要通过typedef指针类型来混淆每个人。指针类型修饰符在每次使用时都可见,这是很常见的,只是为了表明它 一个指针。但现在是实际答案:

node *start;
node *current;
typedef struct node{
    int value;
    node *next;
};

从第一行开始:您在这里使用 node 作为类型标识符。但是您还没有告诉编译器 node 应该是哪种类型。事实上,您实际上缺少的 前向声明。它会像下面这样工作:

/* forward-declare "struct node" and at the same time define the type
 * "node" to be a "struct node":
 */
typedef struct node node;

/* now use your type by declaring variables of that type: */
node *start;
node *current;

/* finally fully declare your "struct node": */
struct node {
    int value;
    node *next;
};

或者,如果没有 typedef,这很容易让初学者感到困惑:

struct node; /* forward declaration (not strictly necessary in this little example) */

struct node *start;
struct node *current;

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