C语言 分割错误:实现双向链表数据结构时出现 11 错误



在实现此双向链表数据结构时,我收到分段错误: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 错误

您必须在从用户那里获取整数数组的大小后声明它。

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]);
}

最新更新