【发布时间】:2015-03-17 23:25:56
【问题描述】:
我正在尝试使用一个简单的链表示例,以尝试了解使用它们背后的基本思想,以供以后使用。但是,我对如何将列表中的每个节点设置为某个值感到困惑。即在这里,我想将成员“a”设置为“b”的地址,将成员“b”设置为c的地址。但是,这是发生警告的地方,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct List
{
int data;
struct List * next;
};
int main (int argc, char * argv[])
{
struct List * a = malloc(sizeof(struct List));
a->data = 0;
a->next = NULL;
struct List * b = malloc(sizeof(struct List));
b->data = 1;
b->next = NULL;
struct List * c = malloc(sizeof(struct List));
c->data = 2;
c->next = NULL;
a->next = &b; //warning occurs here
b->next = &c;
}
有没有办法在没有任何警告的情况下设置 a->next (a.next) 和 b->next(b.next) 的值?
【问题讨论】:
-
您希望
a->next指向b指向的 malloc 分配的空间。不要指针b. -
那么第一个和最后一个(malloc 调用)就可以了吗?只有 * b 一个?
-
所有 malloc 调用都很好,问题是给你警告的两行
标签: c pointers struct linked-list