【发布时间】:2018-03-24 07:17:40
【问题描述】:
#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 工作吗?谢谢
【问题讨论】:
-
您从哪里了解到
static和extern的这种用法?这是语言的非惯用用法并且容易出错。无论如何,你的问题是题外话,原因是明确的(“为什么这段代码不起作用?”)。 -
@axiac 问题之一是它不起作用,因此它与代码审查无关。在将用户重定向到 Code Review 之前,请阅读 our guide for SO migration。
-
@Zeta 明白了。感谢您指出这一点。