【发布时间】:2013-08-31 14:55:01
【问题描述】:
更新: 我已将静态数组更改为动态数组,但仍然收到段冲突错误,尽管 eclipse 说:
*** glibc detected *** (path to file) double free or corruption (!prev): 0x00000000004093d0 ***
StructHashTable 是一个类型定义...
int main() {
...
StructHashTable *B0 = (StructHashTable *) malloc(N_ELEMS*sizeof(StructHashTable));
...
}
void resizeHash(StructHashTable *hash) {
int size = currentElements + N_ELEMS;
StructHashTable newHash[size];
int i;
for (i = 0; i < size; i++) newHash[i].key = FREE;
for (i = 0; i < currentElements; i++) insertHash(newHash, hash[i]);
currentElements = size;
hash = (StructHashTable *) realloc(hash, size*sizeof(StructHashTable));
if (hash != NULL) {
for (i = 0; i < size; i++) hash[i] = newHash[i];
}
}
现在怎么了?我是否以不好的方式使用 realloc?要不然是啥? C 快把我逼疯了……
旧: 我正在做大学作业,我需要在 C 中调整一个静态数组的大小,它必须是静态的,调试器说段违规......
我有一个声明数组的主函数...
// File: main.c
int main() {
...
StructHashTable hash[N_ELEMS];
...
}
在运行时的某个时刻,我需要比 N_ELEMS 更多的元素,并且我已经在 HashTable.c 中编写了一个函数来执行此操作,这就是方法:
// File: HashTable.c
#define N_ELEMS 32
int currentElements = N_ELEMS
void resizeHashTable(StructHashTable *hash) {
int size = currentElements + N_ELEMS;
StructHashTable newHash[size];
int i;
// Inicialize newHash
for (i = 0; i < size; i++) newHash[i].key = FREE;
// Insert old hash elements to the new table...
for (i = 0; i < currentElements; i++) {
insertHash(newHash, hash[i]);
}
currentElements = size;
// I've tried making hash null with no luck...
//hash = NULL;
//free(hash);
// HERE'S THE ERROR...
hash = newHash;
// I've tried *hash = *newHash with the same result...
}
有人能告诉我该怎么做吗?
谢谢。
【问题讨论】:
-
无法调整静态分配数组的大小。你的作业可能不会这么说。
-
可能是设计问题?因为作业说得很清楚......
-
如果您的作业是用英语写的,请考虑在您的答案或评论中发布该部分。 无法调整分配的大小。 您唯一能做的就是复制新分配的内存中已有的内容并释放旧的分配;但这意味着您需要动态分配。
-
作业准确地说是:记录使用依赖于键的哈希表存储,表的初始大小为 32 个元素,填充时相应扩展。
-
所以,它没有说任何关于静态数组的内容。只有你必须选择初始数组大小,这可以很容易地用动态的来完成。将哈希表实现为静态数组会限制您增加其初始大小。解决方案是将静态数组更改为动态数组。