更新:我已经将静态数组更改为动态数组,但我仍然收到段违规错误,尽管 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快把我逼疯了...
OLD:我正在做大学作业,我需要在 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...
}
有人可以告诉我如何做我想做的事吗?
谢谢。