我已经用 C++ for Windows 编写了一段类似的代码,其中创建了一个基本的单链表、添加数据并显示列表的内容。这次我尝试用 C 为 Linux 编写一个类似的程序。似乎没有编译器错误或运行时错误,但是当我尝试调用函数 void insert()
时,程序控制台告诉我存在段错误。
我的代码包含在下面:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}*nPtr;
nPtr head = NULL;
nPtr cur = NULL;
void insert(int Data);
void display();
int main(void)
{
int opr, data;
while (opr != 3)
{
printf("Choose operation on List. \n\n1. New Node. \n2. Display List.\n\n>>>");
scanf("%d", opr);
switch (opr)
{
case 1 :
printf("Enter data.\n");
scanf("%d", data);
insert(data);
break;
case 2 :
display();
break;
case 3 :
exit(0);
default :
printf("Invalid value.");
}
}
getchar();
}
void insert(int Data)
{
nPtr n = (nPtr) malloc(sizeof(nPtr));
if (n == NULL)
{
printf("Empty List.\n");
}
n->data = Data;
n->next = NULL;
if(head != NULL)
{
cur= head;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = n;
}
else
{
head = n;
}
}
void display()
{
struct Node* n;
system("clear");
printf("List contains : \n\n");
while(n != NULL)
{
printf("\t->%d", n->data, "\n");
n = n->next;
}
}
当我运行代码时,似乎没有任何问题或错误。但是当我调用我在那里创建的两个函数中的任何一个时,出现一个错误,提示“段错误”。我认为 void insert()
中的 malloc()
函数会出现问题,但我无法确定 void 中的问题所在display()
方法。
最佳答案
display()
函数从不初始化n
。声明应该是:
nPtr n = head;
关于c - 无法在Linux中使用C创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954772/