C 打印链表不起作用?

标签 c file-io linked-list scanf

我正在读取文件并尝试将其添加到链表中,然后遍历链表以打印出内容。我有点麻烦,因为我的输出不是打印整个链表,而是多次打印最后一个元素。我已经在下面发布了代码并且我只发布了片段,并且为了简洁删除了错误检查。

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 复制字符串 (strncpy()) 到 newNode->data

使用 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).

关于C 打印链表不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269681/

相关文章:

python - open() 给出 FileNotFoundError/IOError : Errno 2 No such file or directory

java - 哪个更好 - 使用 String 或 File 作为采用文件名的方法的参数类型

java - BufferedWriter 不会抛出任何错误,但文件为空

C:删除双向链表中的第一项时出现段错误

java - 计算链接列表中给定数字的出现次数

c - Scanf 中 & 运算符的使用

c - 如何在 MATLAB MEX 文件中使用 FFTW lib 文件?

java - 链表在中间插入

c - FFmpeg vaapi_transcode 示例执行错误

C程序打印目录中的目录名并排除当前目录和父目录