about 2-D arrays in GNU MP

David Gillies daggillies at gmail.com
Thu Jan 22 21:37:05 CET 2009


On Thu, Jan 22, 2009 at 1:43 AM, souvik bhattacherjee
<souvik99 at gmail.com> wrote:
> Though I have been successful in creating 2-D arrays in GNU MP which is as
> follows:
>
> mpz_t A[N][N];
>
> mpz_array_init(A[0][0], NOC, SIZE);
>
> I was not successful in passing this 2-D array to a function. Can anyone
> please suggest how to achieve this.
>
> I have tried some constructs. Say, this construct
> ********************************
> func(&A);
>
> void func( mpz_t  *A)
> { }
> ********************************
>
> does not work. Neither does this one
>
> ********************************
>
> func(A);
>
> void func( mpz_t A[ ][ ])
> { }
>
> *******************************
>
> work out.
>

The type of m[z_t A[N][N] is mpz_t[][N]

Multidimensional arrays passed as arguments in C are only allowed to
omit the first size paramater. The argument type for an array (e.g.)
mpz_t A[3][3] is mpz_t[][3]. This is so the compiler can tell the
stride of the matrix so that pointer arithmetic will work inside the
function. This means you need a separate function for each size your
array can be.

For 2D arrays it is a much better bet to dynamically allocate memory.

mpz_t **A;
size_t n;

A=malloc(n*sizeof(mpz_t*));
a[0]=malloc(n*n*sizeof(mpz_t));
for(int i=1;i<n;i++)
   A[i]=A[i-1]+(n*sizeof(mpz_t));

Even better, embed it in a struct to carry round size info

typedef struct GMPMatrix
{
   unsigned int msize;
   mpz_t  **mdata;
} GMPMatrix;

Better still, use C++ and declare a vector<vector<mpz_class> >


-- 
David Gillies
San Jose
Costa Rica


More information about the gmp-discuss mailing list