我尝试使用带有1009个桶的HashTable在C中实现一个简单的数据库表,这些桶包含元组的TupleList(链接列表)。
除非我释放我使用的元组的记忆,否则一切似乎都在起作用。表格打印然后打印出unicode盒子和其他随机的jargons,但特别是,只有一个左右的元组条目。
元组,元组列表,哈希表的定义如下:
struct Tuple {
char *Course;
int StudentId;
char *Grade;
TupleList next;
};
typedef struct Tuple Tuple;
typedef struct Tuple *TupleList;
typedef TupleList HashTable[1009];
元组由:
分配Tuple *createCSGTuple(char *course, int id, char *grade){
Tuple *tuple = (Tuple*)malloc(sizeof(Tuple));
tuple->StudentId = id;
tuple->Course = course;
tuple->Grade = grade;
return tuple;
}
插入方法:
void insert(Tuple *tuple, int key){
if(CSGTable[key] != NULL){//if there is already tuple(s) in the bucket
tuple->next = CSGTable[key];//insert first
CSGTable[key] = tuple;
}else{
CSGTable[key] = tuple;
}
}
打印方法:
void printCSGTable(){
int key = 0;
printf("\nCourse StudentId Grade\n");
while(key < 1009){ //loops through every bucket
if(CSGTable[key] != NULL){
//temp Tuple for printing
Tuple *temp = CSGTable[key];
while(temp != NULL){
printf("%-10s%-13d%-5s\n", temp->Course, temp->StudentId, temp >Grade);
temp = temp->next;
}
}
key++;
}
}
测试代码(其中CSGKey是一个哈希函数,返回一个以Course和StudentId作为参数的键):
Tuple *CSGtuple1 = createCSGTuple("CS121", 12345, "A");
Tuple *CSGtuple2 = createCSGTuple("CS121", 67890, "B");
Tuple *CSGtuple3 = createCSGTuple("EE100", 12345, "C");
Tuple *CSGtuple4 = createCSGTuple("EE100", 22222, "B+");
insert(CSGtuple1, "CSG", CSGKey(CSGtuple1->Course, CSGtuple1->StudentId));
insert(CSGtuple2, "CSG", CSGKey(CSGtuple2->Course, CSGtuple2->StudentId));
insert(CSGtuple3, "CSG", CSGKey(CSGtuple3->Course, CSGtuple3->StudentId));
insert(CSGtuple4, "CSG", CSGKey(CSGtuple4->Course, CSGtuple4->StudentId));
printCSGTable(); //BEFORE FREEING
free(CSGtuple1);
free(CSGtuple2);
free(CSGtuple3);
free(CSGtuple4);
printCSGTable();//AFTER FREEING
输出:
Course StudentId Grade
CS121 67890 B
EE100 22222 B+
EE100 12345 C
CS121 12345 A
Course StudentId Grade
CS121 67890 B
EE100 22222 B+
EE100 12345 C
@}~ 8266304 A
如果我像这样切换免费:
free(CSGtuple2);
free(CSGtuple3);
free(CSGtuple4);
free(CSGtuple1);
OUTPUT 变为:
Course StudentId Grade
CS121 67890 B
EE100 22222 B+
EE100 12345 C
CS121 12345 A
Course StudentId Grade
@}▒ 13509184 B
EE100 22222 B+
EE100 12345 C
@}▒ 13509184 A
根据我的理解,所有信息都已传输到哈希表,因此不再需要元组。
我不确定这个错误发生在哪里,因为它似乎偶尔发生,而不是每个元组或Grade属性。任何帮助或建议将非常感谢!
如果有什么不清楚的话,请随意编辑(特别是标题,因为我不知道如何说出这个错误!)。