簡體   English   中英

了解C中的鏈表

[英]Understanding linked lists in C

我最近開始學習鏈接列表,我想知道關於代碼的兩件事:

  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之后或顯式初始化下一個指向NULL的指針。

我將您的代碼更改為:

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

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

void print(node *head){
    node *temp = head;

    while(temp){
        printf("day:%s\nmonth:%s\nyear:%s\n",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));
    printf("day:\n");
    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->day=malloc(n+1);
    strcpy(new_node->day,temp);

    printf("Month:\n");
    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->month=malloc(n+1);
    strcpy(new_node->month,temp);
    printf("Year:\n");
    fgets(temp,sizeof(temp),stdin);
    n=strlen(temp);
    new_node->year=malloc(n+1);
    strcpy(new_node->year,temp);

   /// new_node->next=head;///

    printf("\n\n\n");
    //printf("%s%s%s \n",new_node->day,new_node->month,new_node->year);

    return new_node;
}
int main(int argc,char* argv[])
{

    node* head=NULL;
    head=malloc(sizeof(node));
    if (head == NULL)
    {
        printf("NULL\n");///cant allocate memory
    }
    printf("this\n");
    head=add(head); 
    print(head);
    return 100;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM