【问题标题】:using c struct to implement linked list使用c struct实现链表
【发布时间】: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


【解决方案1】:

你在这个循环中使用了本地对象newBox

for (int i = 0; i < 3; i++)
{
    struct Box newBox;
    scanf("%d", &(newBox.amount));
    newBox.previous = addressKeeper;
    addressKeeper->next = &newBox;
    addressKeeper = &newBox;
}

在访问此对象的循环调用未定义的行为后,因为它不再存在。

您的程序似乎输出了该本地对象的相同地址。

您要么需要动态分配节点,要么使用循环前声明的节点数组。

【讨论】:

    【解决方案2】:

    您没有在循环中正确创建新的 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];
       }
    

    但是,您需要仔细检查下一个和上一个指针分配。那里还有一些我没有改变的地方。

    【讨论】:

    • 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多