我在 C 中有一个链接列表。我想根据“库存水平”动态填充它。出于测试目的,我创建了一个小程序。这里的库存水平只是简单地硬编码为 1,但足以演示。
在这段代码中,链表中的第一个节点是特殊的,所以我自己创建它并且它始终保持不变。其余节点(其数量与“库存水平”匹配)是动态创建的。
我知道问题与范围有关,但我真的不确定如何。
如果我将“库存水平”设置为 0,一切正常。输出如下所示:
inside function: (5, 10)
outside function: (5, 10)
如果我将“库存水平”增加到 1,输出如下所示:
inside function: (5, 10) ; Correct
inside function: (2, 3) ; Correct
outside function: (5, 10) ; Still Correct
outside function: (24, 48) ; What..?
outside function: (0, 1)
outside function: (1848777136, 32767)
我尝试malloc
链表的头部,但我得到了类似的结果。我也尝试过 malloc
每个结构的 .next
部分,同样得到类似的结果。我一直试图解决这个问题一段时间,最后只是做了一个内联 for 循环来处理这个问题,但我真的希望它在一个单独的函数中(因为我一直不得不重复那段特定的代码 a几个地方)。
感谢您的帮助。
作为引用,这是我正在使用的代码:
#include <stdlib.h>
struct Item {
int x;
int y;
struct Item *next;
};
void create(struct Item *start, int stock) {
*start = (struct Item){ .x = 5, .y = 10, .next = NULL };
int i;
struct Item *previous = start;
for (i = 1; i <= stock; i++ ) {
previous->next = &(struct Item){ .x = (i*2), .y = (i*3), .next = NULL };
previous = previous->next;
}
struct Item *node = start;
while (node != NULL) {
printf(" inside function: (%d, %d)\n", node->x, node->y);
node = node->next;
}
}
int main() {
struct Item head;
int stock = 1;
create(&head, stock);
struct Item *node = &head;
while (node != NULL) {
printf("outside function: (%d, %d)\n", node->x, node->y);
node = node->next;
}
return 0;
}
最佳答案
线
previous->next = &(struct Item){ .x = (i*2), .y = (i*3), .next = NULL };
存储当您退出 for
循环时超出范围的局部堆栈变量的地址。此后,访问内存会导致未定义的行为。一个可能的问题是您的程序的其他部分将写入相同的堆栈位置。
您可以通过为列表元素动态分配内存来解决这个问题
previous->next = malloc(sizeof(*previous->next));
if (previous->next == NULL) {
/* handle out of memory */
}
*previous->next = (struct Item){ .x = (i*2), .y = (i*3), .next = NULL };
如果这样做,请注意您需要调用 free
以便稍后将此内存返回给系统。
关于c - 使用函数为链表创建项目时丢失数据(并添加随机节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000442/