【发布时间】:2014-05-02 16:48:37
【问题描述】:
如何强制 Realloc 表现得像 calloc? 例如:
我有以下结构:
typedef struct bucket0{
int hashID;
Registry registry;
}Bucket;
typedef struct table0{
int tSize;
int tElements;
Bucket** content;
}Table;
我有以下代码来增加表格:
int grow(Table* table){
Bucket** tempPtr;
//grow will add 1 to the number available buckets, and double it.
table->tSize++; //add 1
table->tSize *= 2; //double element
if(!table->content){
//table will be generated for the first time
table->content = (Bucket**)(calloc(sizeof(Bucket*), table->tSize));
} else {
//realloc content
tempPtr = (Bucket**)realloc(table->content, sizeof(Bucket)*table->tSize);
if(tempPtr){
table->content = tempPtr;
return 0;
}else{
return 1000;//table could not grow
}
}
}
当我执行它时,表会正常增长,并且其中的大部分“桶”被初始化为 NULL ptr。然而,并不是所有的都是。
如何让 Realloc 表现得像 calloc?从某种意义上说,当它创建新的“桶”时,它们初始化为 NULL
【问题讨论】:
-
调用 ::memset 清除重新分配内存的多余部分?
标签: dynamic initialization dynamic-memory-allocation realloc calloc