为什么允许结构具有“指向其自身类型的指针"?作为成员而不是“结构类型(的数组)"本身? [英] Why a structure is allowed to have "pointer to its own type" as member but not "(an array of the) structure type" itself?

查看:153
本文介绍了为什么允许结构具有“指向其自身类型的指针"?作为成员而不是“结构类型(的数组)"本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试声明以下函数时

when i try to declare the following function

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE node[26];
}TRIE_NODE;

我收到以下错误:

"struct TRIE_NODE"的定义直到结束}"时才完成.

definition of 'struct TRIE_NODE' is not complete until the closing '}'

但是,如果我用指向26个节点的指针声明此函数,则编译就很好.

However, if i declare this function with a pointer to the 26 nodes, it compiles just fine.

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE* node[26];
}TRIE_NODE;

我想像一下,因为这不是实例,所以我不可能获得指向这26个数组中第一个数组的指针,但是如果这是问题所在,那么TRIE_NODE* node[26]也不是问题吗?这个声明不等于TRIE_NODE node[1][26]吗?

I imagine that, since this is not an instance, it's impossible for me to get a pointer to the first of those 26 arrays, but if that is the problem, how is TRIE_NODE* node[26] not also a problem? Isn't this declaration equivalent to TRIE_NODE node[1][26]?

推荐答案

当我尝试声明以下函数时

等待! 不是函数,而是typedef-结构,用户定义的类型.

Wait!! that's not a function, that's typedef-ing a structure, a user-defined type.

也就是说,在第一种情况下,

That said, in the first case,

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE node[26];  //array of type struct TRIE_NODE
}TRIE_NODE;

如果必须这样做,则编译器需要先定义struct TRIE_NODE 的大小,这是不可能的.因此无效.

if this has to be possible, compiler needs to know the size of the struct TRIE_NODE before it has been defined, which is impossible. So it is invalid.

另一方面,

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE* node[26];  //array of pointers (of type struct TRIE_NODE)
}TRIE_NODE; 

很好,因为您正在向结构分配指针(的数组),所以此时编译器不需要知道结构的实际大小.因此,编译器愉快地分配了指针,并且定义(构造)完全正确.

is fine, as you're allocating (array of) pointers to the structure, the actual size of the structure is not required to be known by compiler at that point. So, the compiler happily allocates the pointers and the definition (construct) is perfectly valid.

这篇关于为什么允许结构具有“指向其自身类型的指针"?作为成员而不是“结构类型(的数组)"本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆