我创建了一个哈希表:
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;
哈希表的每个条目都是链表。然后,在main中我创建一个结构的实例,该结构具有一个结构变量,它是一个哈希表:
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;
}
它运作得很好。
答案 0 :(得分:1)
您正在尝试创建五个链接列表,但您只有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*) );