我必须在C中为一个包含char*key和void*value的映射创建一个结构,它们在内部存储在一起。与其将链表作为外部结构,不如为包含链接指针、键字符串和值(连续)的链表单元格分配内存。
键和值数据必须直接存储在单元中,并且单元必须在运行时构造。我得到了一个包含如下结构的开头:
struct example {
int count_of_list_elem;
void *list;
}
但我不知道这是怎么可能的w/o使用另一个结构来形成链接列表?
我需要在结构本身中创建一些单元格,为它分配内存并传递三个值吗?我只是不确定它会如何工作。
编辑:我需要使用一个void*数组。
最佳答案
这是处理C中动态大小结构的标准方法:
struct example {
struct example *next; /* linked list */
int count_of_list_elem;
char data[1];
}
struct example *bigone = malloc (sizeof (struct example) + 10000);
if (!bigone)
// error
bigone -> next = NULL;
bigone -> count_of_list_elem = 10000;
memcpy (bigone -> data, <data source>);