简体   繁体   English

C打印链表不起作用?

[英]C printing a linked list not working?

I am reading from a file and trying to add it into a linked list and then traversing through the linked list to print the content out. 我正在从文件中读取内容,并尝试将其添加到链接列表中,然后遍历链接列表以将内容打印出来。 I have a little trouble since my output is not printing the entire linked list, but only the last element multiple times. 我有点麻烦,因为我的输出不是打印整个链接列表,而是多次打印最后一个元素。 I have posted code down below and I have posted only snippets, and have removed error checking for brevity. 我在下面发布了代码,并且仅发布了代码片段,并删除了简短的错误检查。

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;
}

So if a file contains some text like "how are you", I am expecting my output to be printed as "how are you", but all I get is "you you you". 因此,如果文件中包含诸如“你好吗”之类的文本,我希望输出的内容将显示为“你好吗”,但我得到的只是“你好你”。 How do I fix this? 我该如何解决?

At

newNode -> data = malloc((1 + strlen(str)) * sizeof(char));
newNode -> data = str;

did you wanted to do a string copy ( strncpy() ) from str to newNode->data ? 您是否要从strnewNode->data进行字符串复制( strncpy() )?

With newNode->data = str; 使用newNode->data = str; the pointer is copied, the contents (eg "how are you") is not copied. 指针被复制,内容(例如“你好吗”) 不被复制。

A simple way might be 一个简单的方法可能是

newNode->data = strdup(str);

From http://man7.org/linux/man-pages/man3/strdupa.3.html 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; is the problem. 是问题。 You're malloc ing space for a string, assigning that address to newNode->data , then immediately overwriting the address to that malloc ed space with the address to str , which actually is the address of buffer all the way from main . malloc ING空间的字符串,分配该地址newNode->data ,然后立即地址到覆盖malloc ED空间的地址str ,这实际上是地址buffer一路之main Not only does this create a memory leak, but it explains your behavior. 这不仅会造成内存泄漏,还可以说明您的行为。 Each time you create a node, you're assigning newNode->data to the address of buffer , so when the last word "you" is stored in buffer , this is the string all the nodes print. 每次创建节点的时候,你要指定newNode->data给的地址buffer ,所以当“你”被存储在最后一个字buffer ,这是字符串的所有节点打印。 What you really want to do is strcpy (or something equivalent) the string from str into your newly malloc ed space. 您真正想要做的是从str到新malloc空间中的字符串strcpy (或等效的东西)。 You should also check the return value of malloc first to make sure it returned a valid pointer: 您还应该首先检查malloc的返回值,以确保它返回了有效的指针:

#include <string.h>
....

if (newNode->data != NULL)
{
  strcpy(newNode->data, str);
}
else
{
   // handle error
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM