c - 将指针传递给函数中的重新分配指针
问题描述
我是一名初学者 C 程序员,在实现(有序)动态结构数组时遇到问题。在向数组添加元素之前,我想检查它是否已满,在这种情况下将其大小加倍:
void insert_translation(dict_entry **dict, char *word, char *translation){
if( dictionary_entries == dictionary_size ){
dict_entry *temp_dict;
temp_dict = realloc(&dict, (dictionary_size *= 2) * sizeof(dict_entry) );
// printf("Increased dict size to %d\n", dictionary_size);
// if(temp_dict == NULL){
// fprintf(stderr, "Out of memory during realloc()!\n");
// /*free(dict);
// exit(EXIT_OUT_OF_MEMORY);*/
// }
//free(dict);
//*dict = temp_dict;
}
dictionary_entries++;
printf("Inserted %s into dict - %d of %d filled.\n", word, dictionary_entries, dictionary_size);
}
我从主函数调用函数,如下所示:
dictionary_size = 2; //number of initial key-value pairs (translations)
dictionary_entries = 0;
dict_entry *dictionary = malloc(dictionary_size * sizeof(dict_entry));
[...]
insert_translation(&dictionary, "bla", "blub");
在我的理解中,字典是指向内存空间的指针。&dictionary 是指向指针的指针,我将它传递给函数。在函数中,dict是指向指针的指针,那么&dict应该是指向内存中区域的指针吧?但是,当我尝试编译时,我收到以下错误消息:
pointer being realloc'd was not allocated
编辑
我扩展了代码示例以在主函数中显示更多代码。
解决方案
问题出在这个语句中
temp_dict = realloc(&dict, (dictionary_size *= 2) * sizeof(dict_entry) );
参数dict
具有类型
dict_entry **dict
在重新分配内存的语句中,您必须使用指针的值,但您正在使用具有类型*dic
的表达式。&dict
dict_entry ***
比较赋值左侧的类型
ict_entry *temp_dict
与重新分配的指针的类型。它们应该是相同的(除了在 C 中,其中一个可以具有 type void *
)
所以你需要写
temp_dict = realloc(*dict, (dictionary_size *= 2) * sizeof(dict_entry) );
^^^^^
在 C 中,参数是按值传递的。如果要更改参数的原始值,则应通过指向参数的指针通过引用传递它。在函数中,您需要取消引用指针以更改指针指向的对象。
推荐阅读
- laravel-5 - 如果记录不存在则插入,如果存在则更新
- c# - Unity3d Photon custom room property problem for making countdown timer
- c# - 为什么 WMI 的结果在标准模式和 Windows 7 中的管理员用户中不同?
- android - 将 MutableLiveData 公开为 LiveData 的正确方法?
- python - How to groupby the keys in dictionary and sum up the values in python?
- php - 我的 php 注册文件在数据库中创建了太多条目
- ios - Adding a custom label to a prototype cell in a split view
- python - Python/Django remove text in variable
- c - 如何在 15 和 18 处处理此警告。“警告:数组下标的类型为 'char' [-Wchar-subscripts]”
- javascript - My class created doesn't export an object