c - 理解 typedef 和 struct

标签 c struct typedef

<分区>

我很难理解这段代码示例:

typedef struct node
{
        int data;
        struct node * next;
} node;

typedef node * nodepointer;

因此,我们正在使用 typedef 构建结构节点...我假设我们这样做是为了在不需要“struct”关键字的情况下初始化结构。

我想问一下为什么在结构定义中我们使用名称“节点”两次(在开始和结束)。

其次,typedef node * nodepointer; 指向什么。在这种情况下是否有必要使用 typedef?这个表达式 node * nodepointer; 不等于吗?

最佳答案

首先,让我们在这里明确一点:typedef 不是变量的声明。它只是将新类型 name 别名为现有类型说明符。

typedef <type specifier> new_type_name;

因此,对于未经训练的人来说,这里发生的事情肯定是骗人的。

struct node 本身是一个名为 nodestruct 具有两个属性 int data 和一个 结构节点 *next.

稍后我将详细介绍 next,但现在这很简单。

然后,周围的 typedef 采用该结构并将其命名为 node。您可能会问,这是为什么?

这是因为在 C 中(与 C++ 不同)通过 tag name 使用结构需要在类型前加上 struct 前缀。

struct Foo {
    // ...
};

Foo bar; // ERROR
struct Foo bar; // OK

使用 typedef,我们使用 typename 为结构别名,称为 node。这个例子应该更清楚一点。

typedef struct Foo {
    // ...
} FooType;

Foo bar; // ERROR
struct Foo bar; // OK

FooType bar; // OK
struct FooType bar; // ERROR

请记住,您可以定义没有标签的结构,因此 typedef 它们。

typedef struct {
    // ...
} FooType;

FooType bar; // OK

虽然我会在您的示例中解释为什么您不能这样做。

示例中的属性 struct node *next 是一个 incomplete type .不完整类型,简单地说,是已经声明(给定名称和类型,即 struct node;)但未定义的类型(给定一个“主体”,即 struct node { int foo; };)。

不完整的类型在定义之前不能使用,除非您指向它们

struct Foo;

struct Foo bar; // ERROR: Foo is not defined.
struct Foo *bar; // OK - it's just a pointer. We know the size of a pointer.

struct Foo {
    // ...
};

struct Foo bar; // OK - it's defined now.

因此,通过声明 struct node *next 类型,我们已经有了 struct node声明,但还没有定义,这使得指向 struct node 的指针成为可能。

您也可以推断,直接使用 struct node起作用:

struct node {
    struct node next; // ERROR - `struct node` becomes infinitely big
    struct node *next; // OK - a pointer is usually 4/8 bytes (we at least know its size at this point)
};

回答你的最后三个问题:

What [does] typedef node * nodepointer; [point] to[?]

没有。它只是另一种类型的别名(标签或“昵称”)。它只是说 nodepointer 类型实际上是一个 node *

这也意味着任何需要 node * 的东西都可以使用 nodepointer,反之亦然。

Is it necessary to use typedef in this case?

没有必要,没有。您也可以到处使用 node * 而不是 nodepointer。大多数编码标准都不赞成将类型定义为指针类型(如您的示例),因为这会增加代码库的困惑(正如您在这个问题中所证明的那样!:))

Is [the] expression node * nodepointer; not equal?

没有。同样,请记住 typedef 只是指定另一种引用同一类型的方法。它实际上并不创建任何内存,而是为现有类型赋予新名称。

关于c - 理解 typedef 和 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199916/

相关文章:

c - c中逐个字符的结构成员

结构硬编码初始化中的 C 结构

简化命名类型的 C++ 语言功能(特别是在函数声明中)

c - 编译时获取结构指针警告的 -Win兼容指针类型

c++ - 内存映射文件 - 如何在其他进程中插入一条数据

c - 尝试在我的程序中使用 libcurl 并出现 "undefined reference"错误

c - 使用 C 在 SVG 中绘制切线图

将 RGB 转换为 YCbCr - C 代码

c++ - 尝试将结构成员函数传递给 atexit

c++ - 指向结构的指针的 Typedef 等价