1

我正在 C 中创建一个(结构的)链表,但我希望能够调用一个函数并让它自己向列表中添加 4-5 个结构。问题是因为在 C 中,函数中创建的所有变量都留在堆栈/堆上,我不知道我应该如何完成这一点。

这是一个代码示例:

struct listItem
{
   int value;
   listItem *left;
   listItem *right;
}

void addItems(listItem *l)
{
   listItem one, two, three;
   l->left = &one;
   one.left = &two;
   two.left = &three;
}

int main (char *a [])
{
   listItem l;
   addItems(l);
}

显然这是行不通的。我怎么能做到这一点?有没有可能。谢谢

编辑:哇,谢谢大家的帮助。这比我想象的更快,更有帮助!

4

3 回答 3

5

您必须使用 malloc() 分配“一”、“二”、“三”,而不是在堆栈上创建它们。完成它们后,您必须再次遍历列表并在内存上调用 free() 以便您的程序不会泄漏。

试试这个 addItem...

void addItem(listItem *l, int value)
{
   listItem* item = malloc (sizeof (listItem));
   item->value = value;
   item->next = 0;
   item->prev = l; // Probably not what you want, but you were only singly linking in the example

   l->next = item;
}
于 2009-06-15T20:50:43.667 回答
3

在这段代码中:

void addItems(listItem *l)
{
   listItem one, two, three;
   l->left = &one;
   one.left = &two;
   two.left = &three;
}

所有变量都留在堆栈上,而不是堆上。可能您想在堆上分配它们,以便您可以引用指向它们的指针,一旦离开堆栈帧就不会无效:

void addItems(listItem *l)
{
   listItem *one=calloc(1, sizeof(*one)), 
     two=calloc(1, sizeof(*two)),
     three=calloc(1, sizeof(*three));
   l->left = one;
   one.left = two;
   two.left = three;
}
于 2009-06-15T20:53:55.033 回答
2

addItems() 必须分配内存:

void addItems(listItem *l)
{
   listItem* one = (listItem*)malloc(sizeof(listItem));
   listItem* two = (listItem*)malloc(sizeof(listItem));
   listItem* three = (listItem*)malloc(sizeof(listItem));
   l->left = 0;
   l->right = one;
   one->left = l;
   one->right = two;
   two->left = one;
   two->right = three;
   three->left = two;
   three->right = 0;
}

int main ()
{
   listItem l;
   addItems(&l);
}

我假设你要创建一个双链表,所以我可以自由地设置左/右指针。如果我的假设有误,请调整以适合您的需求。

干杯

于 2009-06-15T20:54:43.097 回答