gpt4 book ai didi

c - 将哈希表传递给函数时数据丢失

转载 作者:行者123 更新时间:2023-11-30 15:18:36 25 4
gpt4 key购买 nike

我创建了一个哈希表:

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;
}

效果很好。

最佳答案

您正在尝试创建五个链接列表,但您只为其中一个malloc足够的内存:

starbucks->disks_in_system->table = malloc(sizeof(linked_list*));

将该行更改为

starbucks->disks_in_system->table = malloc(5 * sizeof(linked_list*));

或者,更好的是,按照 chux 在注释中建议的方式重新排列初始化代码,以删除其中一个魔数(Magic Number):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com