c - 结构单向链表。为什么这不起作用?

标签 c struct

#include <stdio.h>

struct item {
    int key;
    int data;
    struct item *next;
};

struct item *head = NULL;

int main()
{
    extern void filllist(), printall();
    filllist();
    printall();
    return(0);
}


void filllist()
{
    static struct item a, b, c, d;
    head = &a;
    a.key = 5;
    a.data = 0;
    a.next = &b;
    b.key = 20;
    b.data = 2;
    b.next = &c;
    c.next = &d;
    c.key = 22;
    c.data = 6;
    d.key = 38;
    d.data = 3;
    d.next = NULL;
}

void printall()
{
    static struct item h;
    head = &h;
    for(int i = 0; i < 5; i++) {
        printf("%d: %d\n", h.data, h.key);
        h = h.next;
    }

}

对于 printtall 函数,我收到错误“错误:从类型‘struct item *’分配给类型‘struct item’时类型不兼容”。还有没有固定for循环遍历单向链表的方法吗?我想从 fillist 打印出单向链表。

有人可以帮助我如何让 printtall 工作吗?谢谢

最佳答案

您在这里分配一个指向结构的指针:

h = h.next;

h类型是 struct item但是h.next是指向 struct item指针所以你不能设置 h等于 h.next

也许你想要:

h = *h.next;

打印列表的更好方法是:

void printall(struct item* h)
{
    while (h != NULL) {
        printf("%d: %d\n", h->data, h->key);
        h = h->next;
    }
}

并这样调用它:

printall(head);

除此之外你应该去掉所有的static变量。

例如创建一个添加单个 项目的函数。通常你会使用动态内存(malloc),但这里有一个没有动态内存的例子,即在 main 中定义的所有变量(没有静态变量):

struct item* add_to_front(struct item* h, struct item* n, int key, int data)
{
    n->key = key;
    n->data = data;
    n->next = h;
    return n;
}

并像这样使用它:

int main()
{
    struct item* head = NULL;
    struct item a, b, c;
    head = add_to_front(head, &c, 1, 2);
    head = add_to_front(head, &b, 3, 4);
    head = add_to_front(head, &a, 5, 6);
    printall(head);
    return(0);
}

关于c - 结构单向链表。为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462254/

相关文章:

c - 学习C : what's wrong in my pointer code?

c++ - 可以使用 memcpy() 复制包含指针的结构吗?

c - 与具有灵活数组成员的匿名结构 union

c - 将项目添加到C中的空数组并获取数组长度

c - 内存泄漏与否 - 链表

struct - 如何在调试输出中打印完整的结构路径?

c++ - 将 char 数组类型转换为结构(不是类/对象)

c++ - 如何检测不同的Windows目标平台?

c - 传递类型定义函数指针

c - 如何防止使用 arm-none-eabi-gcc 编译器对该函数进行 vector 运算优化?