问题描述
我正在尝试在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;
}
我做错什么了吗?
解决方法
您在此循环中使用本地对象newBox
for (int i = 0; i < 3; i++)
{
struct Box newBox;
scanf("%d",&(newBox.amount));
newBox.previous = addressKeeper;
addressKeeper->next = &newBox;
addressKeeper = &newBox;
}
在循环访问之后,此对象由于不再存在而调用未定义的行为。
似乎您的程序输出了与该本地对象相同的地址。
您需要动态分配节点或使用循环之前声明的节点数组。
,您没有在循环中正确创建新的Box元素。您有一个struct Box,它在每次循环中都超出范围。您将需要通过malloc()动态分配每个对象,否则分配一个从中绘制的数组。像这样:
struct Box listOfBoxes[3];
struct Box *addressKeeper;
addressKeeper = &listOfBoxes[0];
for (int i = 1; i < 3; i++)
{
scanf("%d",&(listOfBoxes[i].amount));
listOfBoxes[i].previous = addressKeeper;
addressKeeper->next = &listOfBoxes[i];
addressKeeper = &listOfBoxes[i];
}
但是,您需要仔细检查下一个和上一个指针分配。那里仍然有我没有改变的错误。