struct node
{
int coef;
int exp;
struct node *link;
};
typedef struct node *NODE;发布于 2011-10-30 03:58:28
它将NODE定义为struct node *类型的同义词,因此当您声明NODE类型的变量时,实际上是声明了一个指向struct node的指针。
就我个人而言,我不认为这样的声明是一个好主意:你在“隐藏一个指针”(这几乎总是一个坏主意),而且,你没有以任何方式在新名称中突出这一事实。
发布于 2011-10-30 03:57:54
它使NODE成为struct node *的一个类型定义。
发布于 2011-10-30 03:58:30
NODE成为struct node*的别名。
编辑:好的,对于评论(如果我把我的答案写成评论,它会太长,而且没有格式化):
没有不同的方式来写这篇文章。这里,typedef只是用来为指向struct node的指针创建一个同义词/别名。
用法示例如下:
void f()
{
// some code
NODE p = NULL;
// do something with p
// for example use malloc and so on
// like: p = malloc( sizeof( struct node ) );
// and access like: p->coef = ..; p->expr = ..
// do something with p and free the memory later (if malloc is used)
}等同于
void f()
{
// some code
struct node* p = NULL;
// do something with p
}使用NODE使它变得更短(不管怎样,我不建议这样的typedef,因为你在隐藏,它是一个指针,而不是一个struct或其他类型,正如@Matteo Italia的答案所提到的那样)。
您所指的格式:"typedef struct{}type_name format“是另一种格式。这是C中的一种技巧,避免编写struct关键字(因为这在C中是必须的,而在C++中不是)。所以
typedef struct node
{
//..
} NODE;会让struct node成为NODE的别名。因此,与上面的示例相同:
void f()
{
// some code
NODE p;
// do something with p
// note that now p is automatically allocated, it's real struct
// not a pointer. So you can access its members like:
// p.coef or p.expr, etc.
}等同于
void f()
{
// some code
struct node p;
// do something with p
}注意,现在,p is a指针,它是struct node。
https://stackoverflow.com/questions/7941313
复制相似问题