在C中使用malloc为typedef'd类型分配空间
我不确定我需要用什么作为malloc的参数来分配table_allocate(int)函数中的空间。 我只是想count_table * cTable = malloc(sizeof(count_table *)),但是这并不对size参数做任何事情。 我应该为list_node_t分配空间吗? 以下是我正在处理的内容。
在.h文件中我给出了这个签名:
//create a count table struct and allocate space for it //return it as a pointer count_table_t* table_allocate(int);
以下是我应该使用的结构:
typedef struct list_node list_node_t;
struct list_node {
char *key;
int value;
//the next node in the list
list_node_t *next;
};
typedef struct count_table count_table_t;
struct count_table {
int size;
//an array of list_node pointers
list_node_t **list_array;
};
谢谢!
count_table* cTable = malloc(sizeof(count_table*))
是错的。 它应该是
count_table* cTable = malloc(sizeof(count_table));
此外,您还必须分别为list_node_t分配内存。
编辑:
除了Clifford指出为列表节点分配内存外,我认为内存分配还应该考虑列表节点中的char *key 。
你的建议: count_table* cTable = malloc(sizeof(count_table*))只会为指向count_table的指针分配空间。
你需要
count_table* cTable = malloc(sizeof(count_table) ) ;
每个列表节点将被分开分配,并且cTable-> size和cTable-> list_array以及最后一个list_node_t::next更新。 维护一个指向添加的最后一个节点的指针会使添加节点更快。
我不知道为什么count_table::list_array的类型是list_node_t**而不是list_node_t* (并且同样称为list_array而不仅仅是list )。 你的意图是它同时是一个数组还是一个列表? 这会有点多余。 该成员只需要一个指向第一个节点的指针,然后通过list_node::next访问连续的节点
鉴于int是创建的count_table_t的“size”参数,看起来应该既分配count_table_t本身, count_table_t初始化它的成员。
初始化list_array成员还涉及内存分配,因此它看起来像:
count_table_t *table_allocate(int size)
{
count_table_t *table = malloc(sizeof *table);
int i;
table->size = size;
table->list_array = malloc(size * sizeof table->list_array[0]);
for (i = 0; i < size; i++)
table->list_array[i] = NULL;
return table;
}
然而,你还需要检查一些错误条件:乘法size通过sizeof table->list_array[0]可能溢出,要不就是的malloc()的调用可能会失败。 所以这个函数应该看起来像这样:
count_table_t *table_allocate(int size)
{
count_table_t *table;
int i;
/* Check for overflow in list allocation size */
if (size < 0 || size > (size_t)-1 / sizeof table->list_array[0])
return NULL;
table = malloc(sizeof *table);
if (table == NULL)
return NULL;
table->size = size;
table->list_array = malloc(size * sizeof table->list_array[0]);
if (table->list_array == NULL) {
free(table);
return NULL;
}
for (i = 0; i < size; i++)
table->list_array[i] = NULL;
return table;
}
(请注意, (size_t)-1是一个常量,等于size_t的最大值,它是malloc()的参数类型)。
上一篇: Using malloc in C to allocate space for a typedef'd type
