c - 理解 C 中的链表

标签 c linked-list

我最近开始学习链表,我想知道关于我的代码的两件事:

  1. 为什么程序会崩溃?

  2. 为什么它在每个成员的末尾都加上一个换行符 \n

这是我的代码。我只是想添加一个成员并打印出来。

struct node
{
    char* day;
    char* month;
    char* year;
    struct node* next;
};
typedef struct node node;

void print(node* head){
    node* temp=head;
    while(temp != NULL){
    printf("%s %s %s",temp->day,temp->month,temp->year);
    temp=temp->next;
    }
}

node* add(node* head)
{
    node * new_node;
    int n;
    char temp[25];
    new_node = malloc(sizeof(node));

    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->day=malloc(n+1);
    strcpy(new_node->day,temp);

    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->month=malloc(n+1);
    strcpy(new_node->month,temp);

    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->year=malloc(n+1);
    strcpy(new_node->year,temp);

    new_node->next=head;
    return new_node;
}

int main(void)
{
    node* head=NULL;
    head=malloc(sizeof(node));
    if (head == NULL)
    {
        return 1;
    }
    head=add(head); 
    print(head);
    return 100;
}

谁能指出我做错了什么以及我本可以做得更好的地方?

最佳答案

当你做一个

ptr = malloc(sizeof(node)); 

内存已分配但未初始化。这将导致节点结构的下一个指针指向未定义的内容。然后,当您在打印功能中使用它时,程序会崩溃。
放一个

memset(ptr, 0, sizeof(node)) 

在 malloc 之后或将 next 指针显式初始化为 NULL。

关于c - 理解 C 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640930/

相关文章:

谁能解释一下在以下情况下如何分配大小?

c - MPI_BARRIER 不工作

在c中将struct转换为char数组

c++ - 简单解析题

data-structures - 链表和二叉搜索树的区别

java - 在java中使用循环链接队列创建出队方法

python - 查找由 python 脚本调用的出现段错误的 C 模块行

c - 排序的双向链表和插入值

java - 反转链表

c - 链表不打印?