Search code examples
arrayscmpfr

Creating 1D arrays of mpfr_t types in C


I am working with the GNU MPFR library, I write some simple C code.
I am trying to create a one-elemental array of mpfr_t objects:

mpfr_t result;
// (some code that assigned values to the variable 'result')
mpfr_t temparr[1];
temparr[0] = result;
mpfr_clear(result);

And I get the following error:

./library/file.hpp:663:20: error: array type 'mpfr_t' (aka '__mpfr_struct [1]') is not assignable
1 error generated.
Error: Process completed with exit code 1.

What should I modify here? Also - I guess I have to additionally clear the temparr[0] variable too, right?


Since I am here, I might as well ask about dynamical arrays. Later in the code, in another function, I have:

mpfr_t* temparr = new mpfr_t[var];
// some code
for (unsigned int i=0; i < var; i++) mpfr_clear(temparr[i]);
delete[] temparr;

I guess this is alright, no? It is not raising any errors during compilation now, at least...


Solution

  • As described in the MPFR manual:

    The C data type for such objects is ‘mpfr_t’, internally defined as a one-element array of a structure

    This explains that you cannot do assignments of mpfr_t directly.

    Moreover, the mpfr_t array does not contain all the data that define the MPFR number (this is something more or less missing in the manual; this is described in the Internals section, but I suppose that users should not have to read this section to warn them against doing incorrect things). This means that, in general, you are not allowed to just copy the mpfr_t array (e.g. by memcpy). The only safe way to copy MPFR numbers is via the MPFR interface, e.g. mpfr_set.

    Your C++ code seems correct (at least the part you wrote). You may define arrays of mpfr_t.