为什么在我的 C 代码中打印 (null)?

Why is (null) being printed in my c code?

我正在尝试将字符串添加到链表中,但我在打印 (null) 时遇到问题。谁能帮帮我?

我能做的最好的事情就是将问题缩小到这个问题:

struct node *head = malloc(sizeof(struct node));
struct node *ptr = malloc(sizeof(struct node));

代码如下:

#include <stdio.h>
#include <stdlib.h>

struct node {
    char *data;
    struct node *link;
};

struct node *add_begin(char *d, struct node *head) {
    struct node *ptr = malloc(sizeof(struct node));
    ptr->data = d;
    ptr->link = head;
    return ptr;
}

void add_end(struct node *point, char *data) {
    struct node *temp = malloc(sizeof(struct node));
    
    temp->data = data;
    temp->link = NULL;
    
    while (point->link != NULL) {
        point = point->link;
    }
    point->link = temp;
}

int main() {
    struct node *head = malloc(sizeof(struct node));
    struct node *ptr = malloc(sizeof(struct node));
    head->link = ptr;
    char *data = "Chocolate Cake";
    head = add_begin(data, head);
    add_end(ptr, data);
    while (head != NULL) {
        printf("%s \n", head->data);
        head = head->link;
    }
}

输出:

Chocolate Cake
(null) 
(null) 
Chocolate Cake 

问题是您分配了虚拟节点,这些节点未初始化并且恰好具有空指针,如 datalink。该列表最初应为空,即:head 应为空指针。

请注意,add_end 还应 return 头指针,以防传递空列表。强烈建议以相同的顺序将参数传递给两个函数。

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>

struct node {
    char *data;
    struct node *link;
};

struct node *add_begin(struct node *head, char *data) {
    struct node *ptr = malloc(sizeof(*ptr));
    ptr->data = data;
    ptr->link = head;
    return ptr;
}

struct node *add_end(struct node *head, char *data) {
    struct node *ptr = malloc(sizeof(*ptr));

    ptr->data = data;
    ptr->link = NULL;

    if (head == NULL) {
        return ptr;
    } else {
        struct node *temp = head;
        while (temp->link != NULL) {
            temp = temp->link;
        }
        temp->link = ptr;
        return head;
    }
}

int main() {
    struct node *head = NULL;
    char *data = "Chocolate Cake";

    head = add_begin(head, data);
    head = add_end(head, data);

    for (struct node *ptr = head; ptr; ptr = ptr->link) {
        printf("%s\n", ptr->data);
    }
    return 0;
}

输出:

Chocolate Cake
Chocolate Cake