GMP學習:初始化mpz數組

GMP庫中有函數 mpz_array_init ,但是註釋了

This is an obsolete function. Do not use it.

mpz_array_init 的問題在於它永遠不會釋放分配的內存。

看到網上沒有什麼有關的資料,因此記錄一下使用 GMP 初始化數組的方法:

#include <stdio.h>
#include <gmp.h>

int main(void) 
{
    int len = 4;
    mpz_t num_arr[len];

    for (int i = 0; i < len; i++) {
        mpz_init2(num_arr[i], 1024);  // Initialize x, with space for n-bits numbers, and set its value to 0.
        gmp_scanf("%Zd", num_arr[i]);
    }
    
    for (int i = 0; i < len; i++) {
        gmp_printf("%Zd\n", num_arr[i]);
        mpz_clear(num_arr[i]);  // Free the space occupied by num_arr[i].
    }

    return 0;
}

參考

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章