我有以下代码。
我收到错误'list' undeclared (first use in this function)
。
请帮帮我
#include <stdio.h>
#include <stdlib.h>
struct list{
int data;
struct list *next;
};
typedef struct list *head;
int main()
{
struct list *start;
int i;
start = (list *) malloc(sizeof(struct list));
printf("\nEnter the data : \n");
scanf("%d", &i);
start->data = i;
start->next = NULL;
while(list->next != NULL)
{
printf("%d ", list->data);
list = list->next;
}
return 0;
}
答案 0 :(得分:3)
您使用的是list
类型而不是变量名start
。正确的代码:
while (start->next != NULL)
{
start = start->next;
// etc.
}
答案 1 :(得分:3)
Don't cast the return type of malloc
- 它没有任何好处,在这种情况下你做错了!
start = (list *) malloc(sizeof(struct list));
应该是
start = malloc(sizeof(struct list));
类型list *
不存在;你的意思是struct list *
。
您可以通过编写
使其更加安全start = malloc(sizeof(*start));
这样你自动malloc
start
的(指针)类型的足够字节,这在你稍后更改start
的类型 - malloc
调用时很有用没有改变。
答案 2 :(得分:1)
在
start = (list *) malloc(sizeof(struct list));
包含不必要的类型转换。只是做
start = malloc(sizeof(struct list));
但是,您的代码比这更麻烦。我可以通过问自己的问题来最好地回答你的问题:在你看来,list
是一种类型还是一种对象?
如果你回答这个问题,可以怀疑你可以修复你的代码。祝你好运。
答案 3 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
typedef struct list{
int data;
struct list *next;
} list;
typedef struct list *head;
int main()
{
struct list *start;
int i;
start = (list *) malloc(sizeof(struct list));
printf("\nEnter the data : \n");
scanf("%d", &i);
start->data = i;
start->next = NULL;
while(start->next != NULL)
{
start = start->next;
}
return 0;
}
您可以定义类型(列表*)
答案 4 :(得分:1)
您的变量名为«start»,您将其命名为«list»。
答案 5 :(得分:0)
start = (struct list *) malloc ...
你在投射中错过了 struct 。 Anthales指出,这根本不是必需的。
start = malloc ...
答案 6 :(得分:0)
您遇到的一个问题是,在创建了typedef struct list *start;
之后,您正在重新使用struct来声明结构指针。 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;
}