【问题标题】:meaning of a struct within a struct in c [duplicate]c中结构内结构的含义[重复]
【发布时间】:2019-08-07 14:22:03
【问题描述】:

有人能解释一下我们在做什么时的意思吗,比如 struct Node* next 做什么。它会创建一个结构类型的指针吗?任何有关 c 结构的帮助和资源都会有所帮助

struct Node {
    int dest;
    struct Node* next;
};

【问题讨论】:

  • 这是一个典型的结构,用于链表之类的东西。给你,你有搜索词。
  • 在您的示例中,结构中有 no 结构。 nextpointerstruct Node 类型的对象,它与指针所属的结构相同。

标签: c struct graph


【解决方案1】:

"struct" 本身不是一个类型。 “struct [tag]”是一种类型,例如代码中的“struct Node”。

在您的情况下,您定义了一个结构类型。该类型的每个结构都将包含一个指向该类型的另一个结构的指针,作为称为“next”的成员。

这允许您在所谓的链表中将结构链接在一起。您将指向第一个结构的指针存储在一个变量中,然后您可以沿着链接链向下找到您需要的结构。

例如,你可以这样做

struct Node *start;
start = malloc(sizeof struct Node);
start->dest = 7;
start->next = malloc(sizeof struct Node);
start->next->dest = 13;
start->next->next = malloc(sizeof struct Node);
start->next->next->dest = 19;
printf("%d %d %d\n", start->dest, start->next->dest, start->next->next->dest);
free(start->next->next);
free(start->next);
free(start);

请注意,这段代码省略了所有错误处理,在实际代码中你必须处理 malloc 返回 NULL 的情况。

此外,在实际代码中,您将在遍历链的循环中使用这种结构,而不是像上面那样直接使用。

【讨论】:

    【解决方案2】:

    正如@Serge 在 cmets 中指出的那样,它不是 struct 中的 struct,而是对同一类型对象的引用(指针),例如:

    #include <stdio.h>
    
    struct Node {
        int dest;
        struct Node* next;
    };
    
    int main(void)
    {
        /* An array of nodes */
        struct Node nodes[] = {
            {1, &nodes[1]}, // next points to the next element
            {2, &nodes[2]}, // next points to the next element
            {3, NULL}       // next points to null
        };
        /* A pointer to the first element of the array */                           
        struct Node *node = nodes;
    
        while (node) {
            printf("%d\n", node->dest);
            node = node->next; // node moves to the next element
        }
        return 0;
    }
    

    输出:

    1
    2
    3
    

    当然,在我的示例中,使用链表没有任何好处,当我们事先不知道元素的数量时,链表很有用。

    另一个使用动态内存的例子:

    struct Node *head, *node;
    
    node = head = calloc(1, sizeof *node);
    node->dest = 1;
    while (more_elements_needed) {
        node->next = calloc(1, sizeof *node);
        node->next->dest = node->dest + 1;
        node = node->next;
    }
    for (node = head; node != NULL; node = node->next) {
        printf("%d\n", node->dest);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多