【问题标题】:Unable to create a linked list in Linux using C无法使用 C 在 Linux 中创建链表
【发布时间】: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() 方法中的问题。

【问题讨论】:

标签: c data-structures linked-list singly-linked-list


【解决方案1】:

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

nPtr n = head;

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2021-10-13
    • 1970-01-01
    • 2020-04-20
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多