【发布时间】:2011-05-14 05:22:06
【问题描述】:
我不确定我需要使用什么作为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;
};
【问题讨论】:
-
你已经得到了很多好的答案,但还没有人注意到重要的一点:
int是有符号类型,除非你想要负大小,否则你应该使用 @987654328 @,这是由sizeof运算符返回并传递给malloc和朋友的类型,旨在能够存储编译器允许的任何大小的数组的数组索引。你可能想要size_t size而不是int size。
标签: c malloc typedef dynamic-memory-allocation