我的函数返回分段错误错误显然没有错
My function is returning segmentation fault error for aparently nothing wrong
我正在制作一个散列 table 数据结构并且在我的初始化函数上有分段错误。这里的代码:
void allocTableSlots(alu **table, int index){
if(index == MAX)
return;
else{
table[index] = calloc(1, sizeof(alu));
table[index]->registration = -1;
table[index]->next = -1;
allocTableSlots(table, index+1);
}
}
void initializateHashTable(hash *hashing){
hashing = calloc(1, sizeof(hash));
allocTableSlots(hashing->table, 0);
hashing->collisionArea = 690;
}
我的结构是这些:
#define MAX 997
typedef struct alu{
int registration;
char name[80];
char email[80];
int next;
} alu;
typedef struct reg{
alu *table[MAX];
int collisionArea;
}hash;
错误来了:
if(index == MAX)
关于 allocTableSlots()
函数
如果我将 MAX
更改为 MAX-1
或任何其他数字,例如 500
,错误仍然出现在位置 499
之后,所以它看起来不像那样我试图访问数组的无效位置 table
我已经尝试了一个迭代版本(以防我的递归有一些错误)但还是一样
正如评论中所建议的,您很可能应该 return 从 init 函数指向分配块的指针。此外,如果最大存储桶大小已知,就像在您的代码中使用 MAX
,代码将简化为:
...
typedef struct reg {
alu table[MAX];
int collisionArea;
} hash;
hash *initializateHashTable(void) {
hash *t = calloc(1, sizeof *t);
if (!t) return NULL; // check calloc, just in case.
/* Whatever initialization you want to perform. As per your code,
setting registration and next members to -1 */
for (int i = 0; i < MAX; i++) {
t->table[i].registration = t->table[i].next = -1;
}
t->collisionArea = 690; // EDIT: Forgot the collisionArea
return t;
}
我正在制作一个散列 table 数据结构并且在我的初始化函数上有分段错误。这里的代码:
void allocTableSlots(alu **table, int index){
if(index == MAX)
return;
else{
table[index] = calloc(1, sizeof(alu));
table[index]->registration = -1;
table[index]->next = -1;
allocTableSlots(table, index+1);
}
}
void initializateHashTable(hash *hashing){
hashing = calloc(1, sizeof(hash));
allocTableSlots(hashing->table, 0);
hashing->collisionArea = 690;
}
我的结构是这些:
#define MAX 997
typedef struct alu{
int registration;
char name[80];
char email[80];
int next;
} alu;
typedef struct reg{
alu *table[MAX];
int collisionArea;
}hash;
错误来了:
if(index == MAX)
关于 allocTableSlots()
函数
如果我将 MAX
更改为 MAX-1
或任何其他数字,例如 500
,错误仍然出现在位置 499
之后,所以它看起来不像那样我试图访问数组的无效位置 table
我已经尝试了一个迭代版本(以防我的递归有一些错误)但还是一样
正如评论中所建议的,您很可能应该 return 从 init 函数指向分配块的指针。此外,如果最大存储桶大小已知,就像在您的代码中使用 MAX
,代码将简化为:
...
typedef struct reg {
alu table[MAX];
int collisionArea;
} hash;
hash *initializateHashTable(void) {
hash *t = calloc(1, sizeof *t);
if (!t) return NULL; // check calloc, just in case.
/* Whatever initialization you want to perform. As per your code,
setting registration and next members to -1 */
for (int i = 0; i < MAX; i++) {
t->table[i].registration = t->table[i].next = -1;
}
t->collisionArea = 690; // EDIT: Forgot the collisionArea
return t;
}