3

バックグラウンド

GMP ライブラリへの C インターフェイスを使用しており、整数の配列を操作する必要があります。GMP ライブラリの整数の主な型は 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) を使用しているときにこの警告を回避する方法はありますか?

4

2 に答える 2

0

にキャストするだけconstです:

  print_x_array((const x_t *)x_array, 3); // Should be ok
于 2013-10-30T22:30:32.760 に答える