a concerned citizen a concerned citizen - 1 year ago 145
C++ Question

C++ MPFRC++ How to use memcpy() with mpfr::mpreal?

I couldn't find anything related to this question. Suppose I have two

, in the heap, as
new mpfr::mpreal[n]
. I have to use C-style arrays because of a function that calls and uses the arrays. I can't modify it, I tried, but it gives wrong results, plus crashes, it's a fairly big and complicated function for my level. If the arrays can get large (both size and type/precision), I'd like to avoid a loop for copying and I'd like to use
instead. What should I use as the 3rd argument?

I tried
but it always gives
, no matter what I use in
. In the home page I have seen that I can use
to better display this, but how can I use it in

Answer Source

The mpfr::mpreal variable (or array of them) is C++ object, it cannot be copied by memcpy correctly. Use std::copy or loop instead.

The memcpy just copies memory blocks bit-by-bit, which works fine for simple POD C-style data structures. C++ objects should be copied by calling the assignment operator so that object can take of memory allocations, etc. by itself.

The size of mpfr::mpreal is always the same since it just contains pointer to mantissa, which is allocated in heap in different memory location. The memcpy copies just the pointer, it doesn't reallocate mantissa and thus source and destination mpreals will point to the same mantissa in memory. This is exactly what should be avoided. In turn, std::copy takes care of this well - by copying every object in a loop using assignment operator of mpreal class (which does the necessary reallocations, etc.)

(I am author of MPFR C++).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download