【发布时间】:2020-11-05 21:09:31
【问题描述】:
我正在尝试在 c 中实现一个链表。我从用户那里获得输入,将其放入一个名为 Box 的结构中,并使用链表保存输入的顺序。 这是结构:
struct Box
{
struct Box *previous;
struct Box *next;
int amount;
};
这是实现:
void main()
{
struct Box firstBox;
scanf("%d", &(firstBox.amount));
struct Box *addressKeeper;
addressKeeper = &firstBox;
for (int i = 0; i < 3; i++)
{
struct Box newBox;
scanf("%d", &(newBox.amount));
newBox.previous = addressKeeper;
addressKeeper->next = &newBox;
addressKeeper = &newBox;
}
}
但是当我以这种方式打印next盒子的地址时,它们都是一样的吗?
struct Box *ptr = &firstBox;
for (int i = 0; i < 3; i++)
{
printf("%p \n", ptr->next);
ptr = ptr->next;
}
我做错了吗?
【问题讨论】:
-
您将 ptr 设置为等于第一个框的地址,但您从未在 for 循环内推进它,因此您多次打印相同的值。你需要做类似 ptr = ptr->next;在循环内。
-
很抱歉,这是复制粘贴中的错误。我编辑了这个。问题依然存在
标签: c struct linked-list scope doubly-linked-list