C语言 由于分段错误,链接列表未显示

mqkwyuun  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(109)

程序的控制流没有进入创建列表功能,我无法理解。为什么会这样。

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

struct Node{
    int data;
    struct Node *next;
}*head=NULL;

struct Node * createList( int arr[], int n){
       head->data = arr[0];
       head->next = NULL;
       struct Node * last;
       
       last = head;
       for(int i=1; i<n; i++){
                 struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
                 newNode->data = arr[i];
                 newNode->next = NULL;
                 last->next  =  newNode;
                 last = newNode;
                 printf("executed ");
       }
       return head;
}
void Display(struct Node * head){
    struct Node * p = head;
   
    while(p!=NULL){
        printf("%d ", p->data);
        p = p->next;
    }
}
int main()
{
    int arr[]={2,55,2,6,66};

struct Node * result = createList(arr, 5);
Display(result);
return 0;
}

我在createList函数的for循环中声明了一个cout,但它没有在终端中打印,因此控制没有进入函数,我已经尝试了几种方法,但仍然无法解决这个问题。

bf1o4zei

bf1o4zei1#

您的代码尝试在createList中的第一个语句解引用NULL指针:

head->data = arr[0];

此时headNULL,所以head->data没有意义。
您应该 * 首先 * 创建(分配)一个节点,然后才分配给它的data成员。
另外,不应该将head定义为全局变量。这应该是createList的局部变量,因为调用者无论如何都在使用返回的指针,而不是head。我还将节点创建代码移动到一个单独的函数中-这使代码更具可读性。
最后,要填充列表,使用指针指针会很方便,这样你就可以使用相同的代码来设置head和设置next成员:

struct Node * createNode(int data) { // Separate function
    struct Node *newNode = malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

struct Node * createList( int arr[], int n){
    struct Node *head = NULL; // Don't use a global variable for this
    struct Node **ref = &head; // Address of the pointer that needs to be updated
    for (int i = 0; i < n; i++) { // First iteration will set `head`
         *ref = createNode(arr[i]);
         ref = &(*ref)->next; // The address of the tail node's `next` member
    }
    return head;
}

相关问题