c - 函数参数指针数组 (C)

标签 c arrays pointers

在我的代码中我有一个指针数组,其中指针指向我的结构

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/

相关文章:

c - 获取超出范围的数组元素的地址是未定义的行为吗?

java - java中多维数组的减1

C编译器警告: assignment from incompatible pointer type

c - fwrite 失败取决于先前的 fwrite

c - 将数据输入到函数

c - 如何在 C 中解析带有换行符的字符串?

c - 如何在 VS2013 中强制执行 c89 风格的变量声明

php - 使用PHP将2个数组插入mysql

c - 函数指针赋值

c - gcc -O0 仍然优化了 "unused"代码。是否有一个编译标志来改变它?