【发布时间】:2020-05-14 05:22:25
【问题描述】:
我用 C++ 为 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() 方法中的问题。
【问题讨论】:
-
cur没有理由成为全局变量,它应该是insert()的本地变量。 -
使用前先看看scanf()。
-
在
insert()中,这个nPtr n = (nPtr) malloc(sizeof(nPtr));是错误的。应该是nPtr n = malloc(sizeof(struct Node));
标签: c data-structures linked-list singly-linked-list