简体   繁体   English

为什么结构不能成为其自身的成员?

[英]Why can't a struct be a member of itself?

I have a struct foo . 我有一个struct foo Declaring a member of type foo* works: 声明foo*类型的成员可以:

typedef struct foo
{
    struct foo* children[26];
} foo;

But if I try to declare a member of type foo I get an error: 但是,如果我尝试声明foo类型的成员,则会收到错误消息:

typedef struct foo
{
    struct foo children[26];
} foo;

This declaration gives me the error 这个声明给我错误

definition of 'struct foo' is not complete until the closing '}' 直到结束“}”时,“ struct foo”的定义才完整

A structure T cannot contain itself. 结构T不能包含自身。 How would you know its size? 您怎么知道它的大小? It would be impossible to do so, because the size of T would require you to know the size of T (because T contains another T ). 这样做是不可能的,因为T的大小将要求您知道T的大小(因为T包含另一个T )。 This turns into an infinite recursion. 这变成了无限递归。

You can have a pointer to T inside a structure T because the size of a pointer is not the same size as the pointed-to object: in this case, you would just store an address of memory where another T is stored - all the space you need to do that is basically the space you need to store a memory address where another T lives. 你可以有一个指针T的结构里面T ,因为指针的大小是不大小相同的所指对象:在这种情况下,你会只储存在那里另一个内存地址T存储-所有的空间您需要做的基本上是存储另一个T所在的内存地址所需的空间。

The structure Trie cannot contain another structure Trie in it , it will do a never - ending recursion but it may contain a pointer to another structure Trie 结构Trie不能在其中包含另一个结构Trie ,它将进行无休止的递归,但它可能包含指向另一个结构Trie的指针

So first one is correct 所以第一个是正确的

typedef struct TRIE
{
    bool is_endpoint;
    bool is_initialized;
    struct TRIE* children[26];
} TRIE;
  1. Object of type T can't contains another non-static object of same type. 类型T的对象不能包含另一个相同类型的非静态对象。 If it may be possible, how to find size of that object? 如果可能的话,如何找到该物体的尺寸? Size of pointer to object is always constant on current system. 在当前系统上,指向对象的指针的大小始终是恒定的。
  2. Check value of currentptr for non-NULL before you can access fields of currentptr (like is_endpoint ). 在可以访问currentptr字段(如is_endpoint )之前,请检查currentptr值是否为非NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM