链表由于分段错误不显示

问题描述 投票:0回答:0

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

#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,但它没有在终端中打印,因此控制没有进入该函数,我已经尝试了几种方法,但仍然无法弄清楚。

linked-list singly-linked-list doubly-linked-list
© www.soinside.com 2019 - 2024. All rights reserved.