分段错误:实现双链表数据结构时出现11错误

时间:2019-03-30 17:37:15

标签: c data-structures

在实现此双向链接列表数据结构时,我遇到了细分错误:11错误。

我以下面的图片形式发布了我的代码:

#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node* prev ; 
int data ; 
struct node* next ; 
}; 
struct node* first=NULL ; 
void create(int[],int);›
void display(struct node*);
int  main()
{
int A[]={ }; 
int cap ; 

printf("Enter how many elements do you want to insert in the Linked 
List :\n");
scanf("%d",&cap); 

printf("Enter the elements that you want to insert in the Linked List 
in the form of a Array Stream :\n");

for(int i=0 ; i<cap ; i++)
{
    scanf("%d",&A[i]);
}

create(A,cap); 
display(first);

}



void create(int A[],int n)
{
struct node* t ;                                

struct node* last ; 

first=(struct node*)malloc(sizeof(struct node));
first->data=A[0] ; 
first->prev=NULL ; 
first->next=NULL ; 
last=first ; 

for(int i=1 ; i<n ; i++)
{
t=(struct node*)malloc(sizeof(struct node));
t->data=A[i]; 
t->prev=last ; 
t->next=NULL ; 
last->next=t ; 
last=t ; 


}


}

void display(struct node* p ) 
{  
printf("\n");
printf("The Elements that are present in the Linked List are :\n");
while(p!=NULL)
{
    printf("%d-->",p->data);
    p=p->next ; 
}

}

虽然我尝试运行该程序,并假设例如以数组形式在链表中插入2-3个元素,但它工作正常,但是当我尝试插入3个以上元素时,它给了我细分错误:11错误

1 个答案:

答案 0 :(得分:1)

从用户那里获得整数数组后,必须声明它。

printf("Enter how many elements do you want to insert in the Linked 
List :\n");
scanf("%d",&cap); 

int A[cap];

printf("Enter the elements that you want to insert in the Linked List 
in the form of a Array Stream :\n");

for(int i=0 ; i<cap ; i++)
{
  scanf("%d",&A[i]);
}