【发布时间】:2013-11-10 13:42:10
【问题描述】:
背景
我正在使用 GMP 库的 C 接口,我需要操作整数数组。 GMP library is mpz_t 中整数的主要类型,GMP 使用了一个技巧来允许用户在没有显式分配的情况下使用 gmp_z,同时能够将它们作为指针传递。即gmp_z类型定义如下。
typedef struct
{
int _mp_alloc;
int _mp_size;
mp_limb_t *_mp_d;
} __mpz_struct;
typedef __mpz_struct mpz_t[1];
这很好,但是我在将 mpz_t 数组传递给在 const 数组上运行的函数时遇到了麻烦。
示例
为了举例说明这个简单的非 GMP 程序。
#include <stdio.h>
typedef struct {
int x;
} x_struct;
typedef x_struct x_t[1];
void init_x(x_t x) {
x->x = 23;
}
void print_x(const x_t x) {
printf("x = %d\n", x->x);
}
// I'm just printing so taking a const array
void print_x_array(const x_t* x_array, size_t n) {
size_t i;
for (i = 0; i < n; ++ i) {
printf("x[%zu] = %d\n", i, x_array[i]->x);
}
}
int main() {
x_t x; // I can declare x and it's allocated on the stack
init_x(x);
print_x(x); // Since x is an array, pointer is passed
x_t x_array[3];
init_x(x_array[0]);
init_x(x_array[1]);
init_x(x_array[2]);
print_x_array(x_array, 3); // Compile warning
}
程序使用GMP技巧,只是炫耀用法。编译这个程序会给出一个恼人的警告
gcc test.c -o test
test.c: In function ‘main’:
test.c:33:3: warning: passing argument 1 of ‘print_x_array’ from incompatible pointer type [enabled by default]
test.c:17:6: note: expected ‘const struct x_struct (*)[1]’ but argument is of type ‘struct x_struct (*)[1]’
问题
由于我不是 C 专家,请有人能详细说明为什么会发生此警告。更重要的是,有没有办法在仍然使用 mpz_t(或示例中的 x_t)的同时绕过这个警告?
【问题讨论】:
-
print_x_array(&x_array[0], 3)? -
@chux 不起作用
标签: c arrays pointers warnings gmp