【问题标题】:"struct" before already-declared struct已经声明的结构之前的“结构”
【发布时间】:2016-06-19 04:15:10
【问题描述】:

我还是 C 的新手。我知道您可以将已经声明的 struct 用作新的数据类型,例如 intdouble 等。但是,我遇到了这样写的 struct

struct AdjListNode
{
    int dest;
    int weight;
    struct AdjListNode* next;
};

在这个struct中,“next”指针的数据类型是struct AdjListNode*struct 与已经声明的 AdjListNode* 有什么关系?谢谢!

【问题讨论】:

  • 这是一个链表。见stackoverflow.com/questions/4643987/…
  • 你到底在问什么?
  • 它是一个指向这个结构的实例的指针,也可以是self。在这个特定的例子中,它看起来像一个链表,所以 next 将指向链中的下一个结构......
  • AdjListNode 不是数据类型。这是一个结构标签。 struct AdjListNode 是实际的数据类型。 struct AdjListNode *next;next 声明为指向 struct AdjListNode 的指针。
  • 就您的代码而言,struct AdjListNode 是引用该结构的唯一有效方式。只有在 C++ 中,您才能将结构简单地称为 AdjListNode。在plain-old-C 中,您需要一个typedef,然后才能引用没有struct 关键字的结构。

标签: c struct


【解决方案1】:

struct 与已经声明的 AdjListNode* 有什么关系?

答案是c 语法需要它。

你确实不会通过写struct AdjListNode { ... };得到一个类型AdjListNode

AdjListNode 是一个结构体标签,在声明变量时你总是必须使用struct AdjListNode

看这个简单的例子(结构内没有指针):

#include <stdio.h>

struct sSomeName
{
    int x;
};

int main(void) {
    struct sSomeName var;    // OK, variable of type struct sSomeName 
    struct sSomeName* pVar;  // OK, pointer to variable of type struct sSomeName 

    // sSomeName var2;       // ERROR: unknown type name 'sSomeName'

    var.x = 5;
    pVar = &var;

    printf("%d\n", pVar->x);
    return 0;
}

所以如果你想在struct里面添加一个指针,你必须写struct sSomeName,就像你在main里面做的一样,比如:

struct sSomeName
{
    int x;
    struct sSomeName* p;
};

使用 typedef

如果你想要一个名为AdjListNode 的类型,你必须使用typedef

typedef 示例可能如下所示:

#include <stdio.h>

typedef struct sSomeName sSomeName;

struct sSomeName
{
    int x;
    sSomeName* p;
};

int main(void) {
    sSomeName var;
    sSomeName* pVar;

    var.x = 5;
    var.p = NULL;
    pVar = &var;

    printf("%d\n", pVar->x);
    printf("%p\n", (void*)pVar->p);
    return 0;
}

【讨论】:

    【解决方案2】:

    在这里声明了指向结构的指针。这基本上用于实现链表或其他数据结构,如树。

    这并不意味着结构被重新声明。类似声明一个struct变量。

    【讨论】:

      【解决方案3】:

      结构创建如下:typedef struct AdjListNode。示例:

      #include <stdio.h>
      #include <stdlib.h>
      
      typedef struct AdjListNode
      {
          int dest;
          int weight;
          struct AdjListNode* next;
      }AdjListNode;
      
      
      typedef struct Nodo{
          char *nombre;
          int *edad;
          struct Nodo *siguiente;
      }Nodo;
      
      int main(int argc, char **argv) {
          AdjListNode *nodo=malloc(sizeof(AdjListNode));
          nodo->dest=1;
          nodo->weight=2;
          nodo->next=NULL;
          printf("Nodo-->dest: %d", nodo->dest);
          free(nodo);
      }
      

      【讨论】:

      • 问题中没有typedef,所以我认为你的问题与问题相切。另外,第一句中的 typedef 行不完整。
      猜你喜欢
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2017-04-05
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多