我在创建链表数组时遇到困难。我有这个结构
typedef struct node {
int id;
struct node * next;
} t_point;
t_point* array[10];
例如,我想要 array[0] 指向链表的头部,然后填充,对数组的所有空间重复此过程
我明白我需要如何编码,但我无法正确编码。我只是希望有人向我展示并解释语法。
最佳答案
类似这样的事情:
t_point* array[10]
void link_list()
{
int array_length = sizeof(array) / sizeof(t_point*);
// Allocate the memory for the first list item
array[0] = malloc(sizeof(t_point));
// Iterate through each item in `array` and allocate it some memory
for (int i = 1; i < array_length; i++)
{
// Allocate memory for the next item
array[i] = malloc(sizeof(t_point));
// Set the previous item's `next` field to the current item pointed to by `i`
array[i - 1]->next = array[i];
}
// Close the list by adding a NULL pointer
array[array_length - 1]->next = NULL;
}
还记得释放
经过malloc
的内存,否则会出现内存泄漏。我将把这个问题留给你。
关于c - C 中的链表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30620163/