Search code examples
c++arraysgmp

Using mpf_set_ui on a float array stops output (GMP c++)


For a school project I have to do a couple of calculations involving large numbers, that's why I have chosen to use GMP. After encountering strange bugs in my main program I started experimenting in another one. The following code shows what's going wrong:

mpf_set_default_prec(512);
mpf_t t[5];
mpf_init(t[5]);
cout << "This does appear." << endl;
mpf_set_ui(t[4],9);
cout << mpf_get_d(t[4]) << endl;
cout << "This does not, neither is the number 9 printed." << endl;
mpf_clear(t[5]);

So all the output stops after mpf_set_ui. If I try this without an array, so t[5] and t[4] become t, everything works as expected. What am I doing wrong? Are arrays actually allowed in GMP?


Solution

  • You should probably change your code as follows

    mpf_t t[5];
    for(int i = 0; i < 5; ++i) {
        mpf_init(t[i]);
    }
    
    mpf_set_ui(t[4],9);
    cout << mpf_get_d(t[4]) << endl;
    
    for(int i = 0; i < 5; ++i) {
        mpf_clear(t[i]);
    }