我需要一些帮助来理解这种结构:需要帮助了解结构用C
typedef struct std_fifo{
char* name;
struct std_fifo* next;
}std_fifo, *fifo;
随着typedef
我知道,我可以用我的代码编写struct std_fifo
只std_fifo
代替。但是*fifo
呢?
我需要一些帮助来理解这种结构:需要帮助了解结构用C
typedef struct std_fifo{
char* name;
struct std_fifo* next;
}std_fifo, *fifo;
随着typedef
我知道,我可以用我的代码编写struct std_fifo
只std_fifo
代替。但是*fifo
呢?
代码
typedef struct std_fifo{
char* name;
struct std_fifo* next;
}std_fifo, *fifo;
创建两个(非常严重命名)typedef名称,std_fifo
和fifo
。
typedef名std_fifo
相当于类型struct std_fifo
,并且可以代替struct std_fifo
使用:
std_fifo fifo_instance; // creates an instance of struct std_fifo
std_fifo get_fifo(); // declares get_fifo as a function returning an
// instance of struct std_fifo
void read_fifo(std_fifo *);// declares a function taking parameter of type
// pointer to struct std_fifo
typedef名fifo
相当于类型struct std_fifo *
,并且可以代替struct std_fifo *
使用:
fifo fifo_ptr; // creates a pointer to an instance of struct std_fifo
fifo get_fifoptr(); // declares get_fifoptr as a function returning a pointer
// to an instance of struct std_fifo
void read_fifo(fifo); // declares a function taking a parameter of type
// struct std_fifo *
的原因代码像
typdef struct std_fifo { ... } std_fifo;
作品是因为C有四个不同的名字空间标识符:标签,标签名称,struct
和union
成员名称,以及其他一切。 标签名称std_fifo
总是在struct
关键字之前,这是编译器将其与std_fifo
typedef名称区分开来的方式。
使用的typedef几点建议:
虽然它们可以帮助你的代码扫描更好的在某些情况下,使用的typedef实际上可以掩盖你的意图,使各类更难使用。如果类型的用户必须知道其表示(例如访问struct
的成员,或取消引用指针类型,或者在printf
或scanf
调用中使用正确的转换说明符,或者调用函数propertyly等),那么你应该而不是隐藏在一个typedef后面的表示。
如果您决定使用做想要隐藏typedef后面的类型表示,那么您还应该为涉及该类型的任何操作提供完整的API。 C使用FILE
类型执行此操作;不是直接操纵对象,而是将指针传递给各个例程。所以,如果你决定要隐藏struct std_fifo *
typedef名fifo
后面,那么你也应该创建一个API,如:
fifo new_fifo(); // create a new fifo queue
void destroy_fifo(fifo *); // destroy an existing fifo queue
set_name(fifo, const char *); // set the name of a fifo element
char *get_name(fifo); // retrieve the name of a fifo element
fifo push_fifo(fifo); // add an element to the end of the queue
fifo pop_fifo(fifo); // remove an element from the front of the queue
抽象可以是一件好事,但“漏”抽象是比没有抽象的更糟所有。
这是一个结构的有效定义,可以给一个名称和一个指针。
typedef struct std_fifo{
char* name;
struct std_fifo* next;
}std_fifo, *fifo;
在这个代码,其中std_fifo
是一个结构和*fifo
是指针这个结构。
请注意,'std_fifo'是结构类型的类型名称的别名,'fifo'是指向相同结构类型的指针类型的别名。你的评论使它看起来有点像你认为它们是变量。如果你用'static'或'extern'替换了存储类'typedef',那么片段确实会定义或声明一对变量。使用'typedef'的'存储类',它定义了'struct std_fifo'类型的别名。 –
是的,我已经告诉它,它是一个**结构**。我没有说它是结构变量名称或任何其他事物的名称?好的。@JonathanLeffler – Prometheus
好的。我会把它留在“我发现你的语言不明确”,但你知道你的意思。 –
这意味着您可以使用'fifo variablename;'而不是'struct std_fifo * variablename;'或'std_fifo * variablename;'来声明指向结构体的指针。 – mch
所以我可以写'fifo variablename;'或'std_fifo * variablename;' ?它是一样的吗? – iAmoric
请参阅[是否是一个好主意typedef指针](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) - 简洁的答案:No. –