c/c++语言开发共享将项目转换为C中链接列表的末尾

编辑*(晚上8:14) – 抱歉,我更正了我的代码并将其作为一种方法,因此可以更容易理解。

在添加到链表的末尾时,我不确定如何正确地转换结构。 编译此代码会在最后一行给出一个强制警告。 这可能是我的其余代码无法正常运行的原因。

例如:

#include  typedef struct { int data; struct node *next; } node; node *HEAD = NULL; node *addNode(int num) { if (HEAD == NULL) { HEAD = (node *)malloc(sizeof(node)); HEAD->next = NULL; HEAD->data = num; } else { node *newNode; newNode = (node *)malloc(sizeof(node)); newNode->data = num; newNode->next = NULL; node *iter; iter = (node *)malloc(sizeof(node)); iter = (node *)HEAD; while(iter->next != NULL) iter = (node *)iter->next; iter->next = newNode; //warning : warning: assignment from incompatible pointer type } return HEAD; } 

    然后你所有的警告消失了;

     #include  struct node{ int data; struct node *next; }; typedef struct node node; node *HEAD = NULL; int main(int argc, char*argv[]) { int x = 1; int y = 2; if(HEAD == NULL) { HEAD = (node *)malloc(sizeof(node)); HEAD->next = NULL; HEAD->data = x; } else { node *newNode; newNode = (node *)malloc(sizeof(node)); newNode->data = y; newNode->next = NULL; node *iter; iter = (node *)malloc(sizeof(node)); iter = (node *)HEAD; while(iter->next != NULL) iter = (node *)iter->next; iter->next = newNode; //warning : warning: assignment from incompatible pointer type return 0; } } 

    问题是在完全定义结构之前声明“next”是指向“struct node”的指针,因此“next”指向未定义的结构。 如果将“typedef struct {”更改为“typedef struct node {”,则该错误将消失。

    您的代码存在许多问题。 第一个是转换malloc的返回值,并且不正确地引用要为其分配空间的类型的大小:

    HEAD = (node *)malloc(sizeof(node));

    应该被替换

    HEAD = malloc(sizeof(*HEAD))

    由于从void*到任何其他类型的转换始终在C中定义并隐式,因此您不会收到有关所需强制转换的任何警告。 指定sizeof(*HEAD)使编译器在编译时自动选择HEAD的类型,从而减少类型变化时所需的工作量。

    您还应该记住,某些编译器不喜欢匿名结构(即没有声明名称的结构)。 因此,代码

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

    应该被替换

     typedef struct _node { int data; struct _node *next; } node; 

    其中声明了一个名为_node的结构,typedefed为名为node的类型。 并修复了循环引用。

    最重要的是,你不需要为它提供malloc任何空间。

      以上就是c/c++开发分享将项目转换为C中链接列表的末尾相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522035.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐