GMP mpz_array_init is an obsolete function - How should we initialize mpz arrays?

不问归期 提交于 2019-12-05 13:52:25

Simply loop over the array elements and initialize them one by one using mpz_init2 if you want to preallocate memory:

for (i = 0; i < array_size; i++) {
    mpz_init2(num_arr[i], 1024);
}

The problem with mpz_array_init is that it would never release the allocated memory. If you initialize the elements separately, you can free them afterwards:

for (i = 0; i < array_size; i++) {
    mpz_clear(num_arr[i]);
}

What about different method :

/*
http://scicomp.stackexchange.com/questions/3581/large-array-in-gmp
gcc a.c -lgmp
*/
#include <stdlib.h> // malloc
#include <stdio.h>
#include <gmp.h>

#define LENGTH 100000

int main ()
{       
      /* definition */
    mpz_t *A;
    mpz_t temp;

    mpz_init(temp);

    /* initialization of A */
    A = malloc(LENGTH * sizeof(mpz_t));
    if (A==NULL) {
          printf("ERROR: Out of memory\n");
          return 1;
                 }
    // assign
    mpz_set_ui(temp, 121277777777777777); // using temp var 
    mpz_set(A[4], temp);
    mpz_set_str(A[5], "19999999999999999999999999999999999999999999999999992",10); // using string if number > max 

     // check
    gmp_printf ("%Zd\n",A[4]); // 
    gmp_printf ("%Zd\n",A[5]); // 


    /* no longer need A */
   free(A);
   mpz_clear(temp);

        return 0;
}

Is it good ?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!