您遇到的一个问题是您在创建 typedef 后重新使用 struct 来声明您的 struct 指针,struct list *start;
. 此外 struct 和 typedef 不能具有相同的名称。你得到这个:
cc -Wall test.c -o test
test.c: In function ‘main’:
test.c:13: error: ‘list_t’ undeclared (first use in this function)
test.c:13: error: (Each undeclared identifier is reported only once
test.c:13: error: for each function it appears in.)
test.c:13: error: ‘start’ undeclared (first use in this function)
test.c:13: error: ‘cur’ undeclared (first use in this function)
test.c:13: warning: left-hand operand of comma expression has no effect
test.c:16: error: expected expression before ‘)’ token
您可以选择在任何地方使用 struct list 并跳过使用 typedef 的制作。使用 typedef 可以简化代码的读取方式,如下所述:http ://en.wikipedia.org/wiki/Struct_%28C_programming_language%29#typedef
我已经重写了你刚才的内容,以便我可以编译它并更好地理解它,这样我就可以将一些数据放入一个节点中。我记得当我学习 C 时,整个 struct typedef 概念需要一点时间才能深入了解。所以,不要放弃。
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
typedef struct list list_t;
int main()
{
list_t *start, *cur;
int i;
start = (list_t *) malloc(sizeof(list_t));
if (NULL != start)
{
cur = start; /* Preserve list head, and assign to cur for list trarversal. */
printf("\nEnter the data : ");
scanf("%d", &i);
cur->data = i;
cur->next = NULL;
cur = start;
while(cur != NULL)
{
printf("%d ", cur->data);
cur = cur->next;
}
}
else
{
printf("Malloc failed. Program ending.");
}
return 0;
}