1

我不断收到“来自不兼容指针类型的分配”,但我不知道为什么。我认为它看起来不错。我只是想在 C 中做链表的基础知识。

typedef struct{
   int id;
   struct node *next;
} node;

node *root = NULL; // Sets up a root node when the program starts.

create nodes(int id){
   if(root == NULL){
      root = (node*)malloc(sizeof(node));
      root-> id = -1;
      node *nextNode;
      nextNode = (node*)malloc(sizeof(node));
      nextNode -> id = id;
      root-> next = nextNode; // This line is throwing an error.
   }
}

我觉得这很简单,但我不能把手指放在它上面......

4

3 回答 3

5

您的结构实际上是一个未命名的结构typedef-d to node,但您试图struct node稍后引用它(这与您的nodetypedef 不同)。快速解决方法是简单地为结构命名:

typedef struct node {
   int id;
   struct node *next;
} node;

或者,如果您愿意(这完全符合风格),请删除 typedef 并更正您对结构的其他引用:

struct node {
   int id;
   struct node *next;
};

struct node *root = NULL;

create nodes(int id){
   if(root == NULL){
      root = malloc(sizeof(struct node));
      root->id = -1;
      struct node *nextNode;
      nextNode = malloc(sizeof(struct node));
      nextNode->id = id;
      root->next = nextNode;
   }
}
于 2013-03-09T03:08:24.253 回答
2

这里有四点:

第一的。如果必须在结构的字段中包含指针,请添加 的名称struct node(如上面@JamesMcLaughlin 指出的那样)。例如:

typedef struct nodetag { int id; 结构节点标签*下一个;} 节点;

第二。确保您create按预期使用变量类型。我假设用户定义的变量类型create存在于您#define或其他地方。如果不是,这将导致编译器错误。即使你这样做了,这也不会编译,因为你没有s的return语句。returncreate

第三。包含node *root = NULL;在您的功能nodes中。否则,函数nodes将无法识别变量root并导致编译器错误。

第四。在函数的开头声明局部变量。该行将struct node *nextNode;导致 C89 的编译器错误, 因为 C89 不允许在语句之后进行类型声明。然而,C99 允许这种做法。建议在函数开头声明所有局部变量以兼容 C89 和 C99。

于 2013-03-09T03:36:07.547 回答
-1

尝试这个

struct node{
   int id;
   struct node *next;
} ;

struct node *root = NULL; // Sets up a root node when the program starts.

/* Return type is missing in your code*/ create_nodes(int id){
   if(root == NULL){
      root = (struct node*)malloc(sizeof(struct node));
      root-> id = -1;
      struct node *nextNode;
      nextNode = (struct node*)malloc(sizeof(struct node));
      nextNode -> id = id;
      root-> next = nextNode; // This line is throwing an error.
   }
}
于 2013-03-09T03:04:53.993 回答