c - error : request for member 'next' in something not a structure or union. 是什么意思?

标签 c linked-list

我一直在使用链表进行训练,并且编写了以下代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct node *ptr;
struct node
{
    int element;
    ptr next;
};
typedef ptr list;
typedef ptr position;

int main()
{
    struct node nod1;
    struct node nod2;
    struct node nod3;

    nod1.element=87;
    nod2.element=87;
    nod3.element=98;

    nod1.next=&nod2;
    nod2.next=&nod3;
    nod3.next=NULL;

    list L;
    L.next=&nod1;

    printlist(L);

    return 0;
}

void printlist(list l)
{
    position p;
    p=(l)-> next;
    while(p!=NULL)
    {
        printf("%d",(p)-> element);
        p=p->next;
    }
}

我得到的错误是在这个声明中:

L.next=&nod1;

我不明白为什么,因为我已经在代码的开头定义了“list”,并且类型“ptr”也已经定义了:

typedef ptr list;

最佳答案

根据定义,你必须改变

L.next=&nod1;

L->next=&nod1;

因为在您的代码中,Lstruct node * 类型。

为避免混淆,不要typedef 指针。有时,它们变得非常棘手。

接下来,正如 @WhozCraig 先生在下面的评论中指出的那样,一旦您解决了这个问题,您必须将内存分配给 L(或任何指针,就此而言),然后再使用它。否则,使用未初始化的指针调用 undefined behaviour .

关于c - error : request for member 'next' in something not a structure or union. 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29303106/

相关文章:

在指定的初始值设定项中复制数组

c++ - 如何确定 float, double 的有效位宽度 : Is there a standard definition?

c - 在 C 中通过双指针访问结构元素

c++ - 列表不显示来自 txt 文件

c++ - 表达式必须有类类型?

android - 在 Android NDK 上优化应用程序

c++ - c/c++ Linux 相当于 "bool DllMain()"- 但我需要将失败返回给 dlopen()

c - 结构的元素

java - 从我的用户/主类控制链表队列,不起作用

java - 我还必须做什么才能让我的方法处理任何类型的对象