我一直在使用链表进行训练,并且编写了以下代码:
#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;
因为在您的代码中,L
是struct 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/