无法使用 C 在 Linux 中创建链表

Unable to create a linked list in Linux using C

我用 C++ 为 Windows 编写了一段类似的代码,我在其中创建了一个基本的单链表,添加数据并显示列表的内容。这次我尝试用 C 为 Linux 编写一个类似的程序。似乎没有编译器错误或 运行-time 错误,但是当我尝试调用函数 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;
    }
}

当我运行代码时,似乎没有任何问题或错误。但是当我调用我在那里创建的 2 个函数中的任何一个时,会出现一个错误 "Segmentation fault"。我假设 void insert() 中的 malloc() 函数有问题,但我无法确定 void display() 方法中的错误。

display() 函数从不初始化 n。声明应为:

nPtr n = head;