在 C 中将项目强制转换到链表末尾
编辑*(8:14 PM) - 抱歉,我更正了我的代码,并将其改为一种方法,以便更容易理解。
我不确定在添加到链表末尾时如何正确转换结构。编译这段代码在最后一行给了我一个强制转换警告。这可能是我的其余代码无法正常运行的原因。
例如:
#include <stdlib.h>
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;
}
EDIT*(8:14 PM) - Sorry I corrected my code and made this instead a method so it can be more easily understood.
I am not sure how to properly cast a struct when adding to the end of a linked list. Compiling this code gives me an cast warning at the very last line. This may be the reason why the rest of my code does not properly function.
For example:
#include <stdlib.h>
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
您的代码存在许多问题。第一个是转换 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;
Which statements 声明一个名为 _node
的结构,typedef 为名为 node
的类型。并且还修复了循环引用。
最重要的是,您不需要为 iter
malloc
任何空间。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
,然后是所有警告消失;
and then all your warnings goes away;