[英]C printing a linked list not working?
我正在从文件中读取内容,并尝试将其添加到链接列表中,然后遍历链接列表以将内容打印出来。 我有点麻烦,因为我的输出不是打印整个链接列表,而是多次打印最后一个元素。 我在下面发布了代码,并且仅发布了代码片段,并删除了简短的错误检查。
typedef struct Node{
char* data;
struct Node* next;
} NODE;
NODE* head = NULL;
NODE* tail = NULL;
int main(int argc, char* argv[])
{
char buffer[1024];
FILE* fp = fopen(argv[1], "r");
while(fscanf(fp, "%1023s", buffer) == 1)
{
addNode(buffer);
}
print_linked_list(head);
return 0;
}
void print_linked_list(NODE* head)
{
NODE* ptr = head;
while(ptr != NULL)
{
printf("%s ", ptr -> data);
ptr = ptr -> next;
}
}
void addNode(char* str)
{
NODE* newNode = createNode(str);
if(head == tail && tail == NULL)
{
head = newNode;
tail = newNode;
head -> next = NULL;
tail -> next = NULL;
}
else
{
tail -> next = newNode;
tail = newNode;
tail -> next = NULL;
}
}
NODE* createNode(char* str)
{
NODE* newNode = malloc(sizeof(NODE));
newNode -> data = malloc((1 + strlen(str)) * sizeof(char));
newNode -> data = str;
newNode -> next = NULL;
return newNode;
}
因此,如果文件中包含诸如“你好吗”之类的文本,我希望输出的内容将显示为“你好吗”,但我得到的只是“你好你”。 我该如何解决?
在
newNode -> data = malloc((1 + strlen(str)) * sizeof(char));
newNode -> data = str;
您是否要从str
到newNode->data
进行字符串复制( strncpy()
)?
使用newNode->data = str;
指针被复制,内容(例如“你好吗”) 不被复制。
一个简单的方法可能是
newNode->data = strdup(str);
从http://man7.org/linux/man-pages/man3/strdupa.3.html
The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).
newNode->data = str;
是问题。 你malloc
ING空间的字符串,分配该地址newNode->data
,然后立即地址到覆盖malloc
ED空间的地址str
,这实际上是地址buffer
一路之main
。 这不仅会造成内存泄漏,还可以说明您的行为。 每次创建节点的时候,你要指定newNode->data
给的地址buffer
,所以当“你”被存储在最后一个字buffer
,这是字符串的所有节点打印。 您真正想要做的是从str
到新malloc
空间中的字符串strcpy
(或等效的东西)。 您还应该首先检查malloc
的返回值,以确保它返回了有效的指针:
#include <string.h>
....
if (newNode->data != NULL)
{
strcpy(newNode->data, str);
}
else
{
// handle error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.