[英]Array of linked lists in C
I'm having difficulties on making an array of linked lists. 我在制作一系列链接列表时遇到困难。 I have this struct
我有这个结构
typedef struct node {
int id;
struct node * next;
} t_point;
t_point* array[10];
and I want, for example, that array[0] points to the head of a linked list, and then fill with, repeating this process to all spaces of the array 例如,我想让array [0]指向链表的头部,然后填充,对数组的所有空间重复此过程
I understand how I need to code it, but I can't get it right. 我知道我需要如何编码,但是我做错了。 I just want someone to show me and explain me the syntax.
我只希望有人向我展示并解释语法。
Something like this: 像这样:
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;
}
Also remember to free
the malloc
'ed memory otherwise you will get memory leaks. 还请记住
free
malloc
的内存,否则会发生内存泄漏。 I'll leave that up to you. 我留给你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.