什么是正确的指针类型?

时间:2018-06-07 20:21:26

标签: c c99

我有这样的C99代码(但不完全是这个,下面只是演示问题的示例):

// file: const.c

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct MyData {
    int value;
};

struct MyData **createRandomData(size_t n)
{
    assert(n > 0);
    struct MyData **result = calloc(n, sizeof(struct MyData *));
    assert(result != NULL);
    for (size_t i =0 ; i < n; ++i) {
        result[i] = malloc(sizeof(struct MyData));
        assert(result[i] != NULL);
        result[i]->value = rand();
    }
    return result;
}

void freeData(struct MyData* data[], size_t n)
{
    for (size_t i = 0; i < n; ++i) {
        free(data[i]);
    }
    free(data);
}

int isMyDataSumCanBeDividedByX(const struct MyData* data[], size_t n, int x)
{
    long long sum = 0;
    for (size_t i = 0; i < n; ++i) {
        sum += data[i]->value;
    }
    return sum % x == 0;
}

int main()
{
    srand((unsigned)time(NULL));
    const size_t n = rand() % 100 + 1;
    const int x = rand() % 10 + 2;
    struct MyData **data = createRandomData(n);
    const int result = isMyDataSumCanBeDividedByX(data, n, x);
    printf("%s\n", result ? "found it!" : "not found...");
    freeData(data, n);
    return result;
}

当我尝试编译时:     gcc -std = c99 const.c 我收到了以下警告:

const.c: In function ‘main’:
const.c:46:51: warning: passing argument 1 of ‘isMyDataSumCanBeDividedByX’ from incompatible pointer type [-Wincompatible-pointer-types]
     const int result = isMyDataSumCanBeDividedByX(data, n, x);
                                                   ^~~~
const.c:31:5: note: expected ‘const struct MyData **’ but argument is of type ‘struct MyData **’
 int isMyDataSumCanBeDividedByX(const struct MyData* data[], size_t n, int x)
     ^~~~~~~~~~~~~~~~~~~~~~~~~~

我知道我只能做一个类型转换来解决这个问题,但我想了解一下,参数数据应该是什么样的正确类型,以便:

  • 如果没有此警告,它可以接受struct MyData **。
  • 不允许修改MyData内容(即包含const)

任何人都可以解释为什么警告是生成的,而且不是通过使用类型转换而是通过使用正确的指针类型来摆脱它?

0 个答案:

没有答案