c - 链接列表未显示正确的数据

标签 c visual-studio

我正在学习链接列表,因此决定在这里做一些练习,我试图显示列表中输入的数据。我还添加了一条评论以表达我的理解

typedef struct node {
    int num;
    struct node *nextptr;
}Node;

Node *stnode;
void createNodeList(int n);
void displayList();

这是我创建的节点

void createNodeList(int n) {
    Node *tmp;
    int num = 1;

    //allocate memory address to stnode
    Node *stnode = (Node *)malloc(sizeof(Node));

    if (stnode == NULL) {
        printf("Memory error");
    }
    else {
        printf("Input data for node 1:");
        scanf("%d", &num);

        //declare the stnode num field in struct as user input
        stnode->num = num;
        //declare the stnode address of the next node NULL (to be the last node)
        stnode->nextptr = NULL;
        //define the node name as tmp
        tmp = stnode;

        for (int i = 2; i <= n; i++) {
            //allocate node to fnNode
            Node *fnNode = (Node *)malloc(sizeof(Node));
            if (fnNode == NULL) {
                printf("Memory can not be allocated");
                break;
            }
            else {
                printf("Input data for node %d: ", i);
                scanf("%d", &num);

                //declare the node name fnNode num to store user input
                fnNode->num = num;
                //link the fnNode of nextptr to address null
                fnNode->nextptr = NULL;
                //link tmp node to fnNode
                tmp->nextptr = fnNode;

                tmp = tmp->nextptr;
            }
        }
    }
}

这是为了显示它们

void displayList() {
    Node *tmp;
    if (stnode == NULL) {
        printf("List is empty");
    }
    else {
        tmp = stnode;
        while (tmp != NULL) {
            printf("Data = %d\n", tmp->num);
            tmp = tmp->nextptr;
        }
    }
}

当我输入3个数据后,它应该显示我输入的数据。

但它显示“列表为空”

谢谢=)

最佳答案

Node *stnode = (Node *)malloc(sizeof(Node)); 

这样您就可以隐藏全局变量。这就是为什么您不保留全局变量的任何更改。您所做的只是使用了一个与全局变量 stNode 名称相同的局部变量。

该行应该是

stnode = (Node *)malloc(sizeof(Node));

<子> 不要强制转换 malloc 的返回值。应该是

stnode = malloc(sizeof(Node));

或者更清楚

stnode = malloc(sizeof *stnode);

If you compile this program with -Wshadow option then you will get warning regarding this shadowing. Enable all compiler warnings. It helps.

关于c - 链接列表未显示正确的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614689/

相关文章:

java - 如何在 jnr ffi 中使用结构体和结构体

c - 文本文件处理速度

asp.net - 如何在 Visual Studio 2017 中使用 NPM 并安装包?

c - XC8 PIC18 上的 24 位常量指针不起作用

c++ - 将线程移植到 Windows。关键部分非常慢

visual-studio - 我是否可以更改 VSS 升级向导处理 HTTP 分块的方式以防止迁移到 TFS 2013 时出现超时错误?

c# - 在 C# 中使用 Excel 双值

c++ - 用于运算符重载的 Lambda 表达式

c - gcc没有这样的文件或目录错误

c# - 如何制作 System.Configuration.Install.Installer 以从安装项目中获取变量?