今天我来日经贴,还是malloc的问题……
在《数据结构与算法分析》中看到的实现
第一个例子:(开放地址散列表)
结构体定义
struct HashEntry{ ElementType Element; enum KindOfEntry Info;};typedef struct HashEntry Cell;struct HashTbl{ int TableSize; Cell *TheCells;};HashTable InitializeTable( int TableSize ){ HashTable H; int i; if ( TableSize < MinTableSize ) { printf("Table size too samll!\n"); return NULL; } if ( (H = malloc(sizeof(struct HashTbl))) == NULL ) { perror("OUT OF SPACE!"); return NULL; } H->TableSize = TableSize; for ( i = 0; i < TableSize; i++ ) { H->TheCells[i].Info = Empty; } return H;}struct ListNode{ ElementType Element; Position Next;};typedef Position List;struct HashTbl{ int TableSize; List *TheLists;};HashTable InitializeTable( int TableSize ){ HashTable H; int i; if ( TableSize < MinTableSize ) { printf("Table Size Too Small!\n"); return NULL; } if ( (H = malloc(sizeof(struct HashTbl))) == NULL ) { perror("OUT OF SPACE!"); return NULL; }// H->TableSize = NextPrime( TableSize );// 素数大小 H->TableSize = TableSize; if ( (H->TheLists = malloc(sizeof(List)*H->TableSize)) == NULL) { perror("OUT OF SPACE!"); return NULL; } for (i = 0; i < H->TableSize; i++) { if ( (H->TheLists[i] = malloc(sizeof(struct ListNode))) == NULL ) { perror("OUT OF SPACE!"); return NULL; } H->TheLists[i]->Next = NULL; } return H;}