c - 段错误:11 error while implementing Doubly Linked List Data Structure

标签 c data-structures

在实现此双向链表数据结构时,我收到 Segmentation failure: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]);
}

关于c - 段错误:11 error while implementing Doubly Linked List Data Structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55434038/

相关文章:

sql - 嵌入sql的程序出现编译错误

c++ - 4 个 1byte char 到 1 个 4byte int?

Python数据结构 : SQL, XML,或.py文件

r - 在 R 中转换字符串

c++ - 在 C++ 中读取 "tables"

C/C++ : Is there a specific reason why "void" was not simply defined as "typedef struct{} void" (i.一个空结构)具有适当的转换规则?

c++ - LUID_AND_ATTRIBUTES 属性为 3

C : Array of strings - Can input only n-1 strings for an input size of n

Java:返回实际对象与返回引用

data-structures - 关于重构数据结构的好读物