self referential struct definition?

后端 未结 9 1724
死守一世寂寞
死守一世寂寞 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:09

    In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:

    #include 
    #include 
    
    typedef struct Cell {
      int cellSeq;
      struct Cell* next; /* 'tCell *next' will not work here */
    } tCell;
    
    int main(void) {
        int i;
        tCell *curr;
        tCell *first;
        tCell *last;
    
        /* Construct linked list, 100 down to 80. */
    
        first = malloc (sizeof (tCell));
        last = first;
        first->cellSeq = 100;
        first->next = NULL;
        for (i = 0; i < 20; i++) {
            curr = malloc (sizeof (tCell));
            curr->cellSeq = last->cellSeq - 1;
            curr->next = NULL;
            last->next = curr;
            last = curr;
        }
    
        /* Walk the list, printing sequence numbers. */
    
        curr = first;
        while (curr != NULL) {
            printf ("Sequence = %d\n", curr->cellSeq);
            curr = curr->next;
        }
    
        return 0;
    }
    

    Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell on the first line of the typedef but not knowing about tCell until the last line :-) That's how I remember that rule.

提交回复
热议问题