C中的结构混乱 [英] Struct Confusion in C
问题描述
所以我浏览了这个 C 教程,我发现了以下几行代码:
So I was looking through this C tutorial and I found these lines of code:
struct Monster {
Object proto;
int hit_points;
};
typedef struct Monster Monster;
我认为如果是这样的话会更有意义:
And I thought that it would make much more sense if it were like this:
typedef struct {
Object proto;
int hit_points;
} Monster;
我可能完全错了,因为我对 C 很陌生,但我认为这两段代码会做同样的事情.那么他们这样做了,那么有什么理由更喜欢一个吗?或者如果它们不同,是什么使它们不同?谢谢!
I could could be totally wrong, because I am very new to C, but I would assume both these pieces of code would do the same thing. So is they do, then is there any reason to prefer one over the other? Or if they are different, what makes them different? Thanks!
推荐答案
有时第二种形式不起作用.假设你想创建一个 Monster
的链表.使用第一种形式,您可以在 struct
中添加指向下一个 Monster
的指针.
There are times when the second form won't work. Say you want to create a linked list of Monster
s. With the first form, you can add a pointer to the next Monster
in the struct
.
struct Monster {
Object proto;
int hit_points;
struct Monster* next;
};
您不能在第二种形式中这样做,因为 struct
没有名称.
You can't do that in the second form since the struct
doesn't have a name.
这篇关于C中的结构混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!