【发布时间】:2019-05-19 04:32:55
【问题描述】:
我目前正在用 C 语言试验单链表。我写了一个
newNode 函数用于创建节点,printNodes 函数用于打印所有节点 - 如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
int data;
struct Node *next;
};
void printNodes(struct Node *current_node)
{
while(current_node != NULL)
{
printf("Node is: %d\n", current_node->data);
current_node = current_node->next;
}
}
int main()
{
int number_1 = 2;
int number_2 = 3;
int number_3 = 4;
struct Node *head;
struct Node *second;
struct Node *third;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = number_1;
head->next = second;
second->data = number_2;
second->next = third;
third->data = number_3;
third->next = NULL;
printNodes(head);
}
输出正确:
Node is: 2
Node is: 3
Node is: 4
现在我想写一个函数newNode来创建一个新节点,我把我的代码改成这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *newNode(int number_x, struct Node *nextnode)
{
struct Node *tmp_node;
tmp_node = malloc(sizeof(struct Node));
tmp_node->data = malloc(sizeof(struct Node));
tmp_node->data = number_x;
tmp_node->next = nextnode;
return tmp_node;
}
void printNodes(struct Node *current_node)
{
while(current_node != NULL)
{
printf("Node is: %d\n", current_node->data);
current_node = current_node->next;
}
}
int main()
{
int number_1 = 2;
int number_2 = 3;
int number_3 = 4;
struct Node *head;
struct Node *second;
struct Node *third;
head = newNode(number_1, second);
second = newNode(number_2, third);
third = newNode(number_3, NULL);
printNodes(head);
}
编译后我首先得到这个警告信息:
test.c:16:20: warning: incompatible pointer to integer conversion
assigning to 'int' from 'void *' [-Wint-conversion]
tmp_node->data = malloc(sizeof(struct Node));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
输出如下所示:
Node is: 2
它只显示节点head,我猜next指向有问题
(例如head->next = second),但有什么问题?我无法解决这个问题。
谢谢
【问题讨论】:
-
仅供参考,当你这样做时,问问自己
second在main中的值是多少:head = newNode(number_1, second);?如果您的答案是“我不知道”,那么您与您的程序在同一页面上,因为它也不是。指针保存值(恰好是地址)。如果没有正确分配它们(在这种情况下构建您的列表向后),您正在加载具有不确定值的结构next成员,稍后对其进行评估会调用未定义的行为 .关于您的错误,您为什么要为int数据成员分配内存地址? -
您的错误与问题无关,但这是一个问题,因为您正在泄漏内存 -
tmp_node->data是int并且不需要为其分配内存......尤其是作为你在后面的行覆盖它的内容 -
@WhozCraig
second我猜没有值,它只是一个已初始化的节点,因为我希望head指向secondwith 节点(如ex1).. 所以我猜 second 的输入是空的? -
@s.r.换一种方式。如果我写
int x; printf("%d\n", x);,你希望打印什么?这里唯一正确的答案是“我们不知道 x 是什么,所以我们不知道”。第二个代码列表中的second和third指针也是如此。在您使用它们时,它们没有被赋予确定的值,因此将它们的值用作函数的输入是没有意义的。现在,考虑一下如果您使用与现在相同的调用(但顺序相反)向后(第三个,然后是第二个,然后是头部)构建节点会发生什么。想想吧。
标签: c linked-list int nodes singly-linked-list