我创建了一个哈希表:
typedef struct _linked_list_{
struct _linked_list_ *next;
char *disk_name;
struct disk *disk_object;
} linked_list;
typedef struct _hash_table_ {
int size;
linked_list **table;
} hash_table;
哈希表的每个条目都是一个链表。然后,主要是创建一个结构实例,该实例的结构变量是哈希表:
int main() {
health_monitor *starbucks;
starbucks = malloc(sizeof(health_monitor));
starbucks->id = "92838382";
// THIS IS THE HASH TABLE!
starbucks->disks_in_system = malloc(sizeof(hash_table));
starbucks->disks_in_system->table = malloc(sizeof(linked_list));
starbucks->disks_in_system->size = 5;
//initializing the first 5 rows to be NULL
starbucks->disks_in_system->table[0] = NULL;
starbucks->disks_in_system->table[1] = NULL;
starbucks->disks_in_system->table[2] = NULL;
starbucks->disks_in_system->table[3] = NULL;
starbucks->disks_in_system->table[4] = NULL;
//Making sure that the table rows were created correctly and contain NULL
int counter;
for(counter=0; counter <5; counter++){
printf("The table row is: %s\n", starbucks->disks_in_system->table[counter]);
}
//passing the hash table into explore_current_directory function
explore_current_directory(starbucks->disks_in_system, data_directory);
return 0;
}
for循环内打印表行的print语句给出以下输出:
The table is: (null)
The table is: (null)
The table is: (null)
The table is: (null)
The table is: (null)
但是,一旦我将哈希表传递到函数中,似乎仅存在前三行。这是函数:
int explore_current_directory(hash_table* hm, char* directory){
DIR *dp;
struct dirent *ep;
char* current_directory;
dp = opendir(directory);
int counter;
for(counter=0; counter <5; counter++){
printf("The table row is: %s\n", hm->table[counter]);
}
return 0;
}
我从上面的for循环内的print语句获得以下输出:
The table row is: (null)
The table row is: (null)
The table row is: (null)
最后两行似乎不存在。
在那之后,我曾经遇到过细分错误,但现在不了(我不知道为什么)。
事实是,当我将上面的函数更改为:
int explore_current_directory(hash_table* hm, char* directory){
int counter;
for(counter=0; counter <5; counter++){
printf("The table row is: %s\n", hm->table[counter]);
}
return 0;
}
它工作正常。
最佳答案
您正在尝试创建五个链表,但是您只能malloc
足够一个表的内存:
starbucks->disks_in_system->table = malloc(sizeof(linked_list*));
将该行更改为
starbucks->disks_in_system->table = malloc(5 * sizeof(linked_list*));
或者更好的是,按照注释中建议的chux重新排列初始化代码,以删除其中一个魔术数字:
starbucks->disks_in_system->size = 5;
starbucks->disks_in_system->table = malloc ( starbucks->disks_in_system->size
* sizeof(linked_list*) );
关于c - 将哈希表传递给函数时数据丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31300430/