self referential struct definition?

后端 未结 9 1490
死守一世寂寞
死守一世寂寞 2020-11-22 11:09

I haven\'t been writing C for very long, and so I\'m not sure about how I should go about doing these sorts of recursive things... I would like each cell to contain another

相关标签:
9条回答
  • 2020-11-22 12:11

    A Structure which contain a reference to itself. A common occurrence of this in a structure which describes a node for a link list. Each node needs a reference to the next node in the chain.

    struct node
    {
           int data;
           struct node *next; // <-self reference
    };
    
    0 讨论(0)
  • 2020-11-22 12:12

    I know this post is old, however, to get the effect you are looking for, you may want to try the following:

    #define TAKE_ADVANTAGE
    
    /* Forward declaration of "struct Cell" as type Cell. */
    typedef struct Cell Cell;
    
    #ifdef TAKE_ADVANTAGE
    /*
       Define Cell structure taking advantage of forward declaration.
    */
    struct Cell
    {
       int isParent;
       Cell *child;
    };
    
    #else
    
    /*
       Or...you could define it as other posters have mentioned without taking
       advantage of the forward declaration.
    */
    struct Cell
    {
       int isParent;
       struct Cell *child;
    };
    
    #endif
    
    /*
        Some code here...
    */
    
    /* Use the Cell type. */
    Cell newCell;
    

    In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.

    If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.

    0 讨论(0)
  • 2020-11-22 12:12

    Another convenient method is to pre-typedef the structure with,structure tag as:

    //declare new type 'Node', as same as struct tag
    typedef struct Node Node;
    //struct with structure tag 'Node'
    struct Node
    {
    int data;
    //pointer to structure with custom type as same as struct tag
    Node *nextNode;
    };
    //another pointer of custom type 'Node', same as struct tag
    Node *node;
    
    0 讨论(0)
提交回复
热议问题