在我的代码中我有一个指针数组,其中指针指向我的结构
struct Container *bucket[sizeOfHashMap];
我有一个函数将返回这些数组指针中的 1 个(例如,它可能返回数组索引 6 处的指针)。作为参数,它需要一个指向 this 指针的指针。该功能可以在这里看到:
struct Container* getWhichBucket(char word[], struct Container **bucket[10]){
int value = 0;
int i = 0;
int size = strlen(word);
int hashIndex = 0;
for(i =0; i < size; i++){
value += (int)word[i];
}
//size of array is worked out by getting memory that array takes up / a slot
hashIndex = value % sizeOfHashMap;
return *bucket[hashIndex];
}
我这样调用函数(其中 test 是一个字符数组)
addToBucket(test, getWhichBucket(test, &bucket));
添加到桶看起来像这样:
void addToBucket(char word[], container **bucket){
container *temp = (struct Container*)malloc (sizeof(struct Container));
strcpy(temp->key, word);
temp->value = 9001;
temp->next = *bucket;
*bucket = temp;
return;
}
但是,当我编译
代码和运行
时,编译器发出警告
,我得到一个段错误
。有谁知道为什么?警告可以在这里看到:
cw.c: In function ‘main’:
cw.c:86:2: warning: passing argument 2 of ‘getWhichBucket’ from incompatible pointer type [enabled by default]
cw.c:37:19: note: expected ‘struct Container ***’ but argument is of type ‘struct Container * (*)[(long unsigned int)(sizeOfHashMap)]’
cw.c:86:2: warning: passing argument 2 of ‘addToBucket’ from incompatible pointer type [enabled by default]
cw.c:56:6: note: expected ‘struct container **’ but argument is of type ‘struct Container *’
最佳答案
addToBucket(test, getWhichBucket(test, &bucket));
正在通过一个
struct Container *(*)[10]
到 getWhichBucket
。正如编译器所说,这是错误的类型。
您可以修复原型(prototype)和实现
struct Container* getWhichBucket(char word[], struct Container *(*bucket)[10]){
int value = 0;
int i = 0;
int size = strlen(word);
int hashIndex = 0;
for(i =0; i < size; i++){
value += (int)word[i];
}
//size of array is worked out by getting memory that array takes up / a slot
hashIndex = value % sizeOfHashMap;
return (*bucket)[hashIndex];
}
或更改调用,但没有简单的方法从 struct Container *bucket[10]
获取 struct Container **bucket[10]
,因此您可能仍想更改 getWhichBucket
的类型和实现。
因为你没有在那里修改bucket
参数,所以不需要传递地址,你可以直接传递struct Container *bucket[10]
,
struct Container* getWhichBucket(char word[], struct Container *bucket[]){
int value = 0;
int i = 0;
int size = strlen(word);
int hashIndex = 0;
for(i =0; i < size; i++){
value += (int)word[i];
}
//size of array is worked out by getting memory that array takes up / a slot
hashIndex = value % sizeOfHashMap;
return bucket[hashIndex];
}
并调用
addToBucket(test, getWhichBucket(test, bucket));
关于c - 函数参数指针数组 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977575/