Arc
Arc

Reputation: 462

Issue with the return type of the `get_mpz_t` function of GNU MP

The GNU MP manual specifies the declaration of the function get_mpz_t:

Function: mpz_t mpz_class::get_mpz_t ()

So I was expecting a mpz_t return type. But running the simple code:

#include <iostream>
#include <gmpxx.h>
using namespace std;

int main (void) {
    mpz_class n;
    n = "12345678901234567890123456789012345678901234567890";
    mpz_t m;
    mpz_init(m);
    m = n.get_mpz_t();
    gmp_printf("m %Zd\n", m);
}

Compiled with

g++ mpz_test.cc -o mpz_test -lgmpxx -lgmp

Produces the error output at line m = n.get_mpz_t():

mpz_split.cc: In function ‘int main()’:
mpz_split.cc:12:4: error: incompatible types in assignment of ‘mpz_ptr {aka __mpz_struct*}’ to ‘mpz_t {aka __mpz_struct [1]}’
  m = n.get_mpz_t();
    ^

Looking at the gmpxx.h code I find the declarations:

// conversion functions
mpz_srcptr __get_mp() const { return mp; }
mpz_ptr __get_mp() { return mp; }
mpz_srcptr get_mpz_t() const { return mp; }
mpz_ptr get_mpz_t() { return mp; }

And, of course, mpz_ptr is defined in gmp.h

typedef __mpz_struct *mpz_ptr;

So, is the manual inaccurate? Or, what am I doing wrong here?

Upvotes: 0

Views: 427

Answers (1)

oltis
oltis

Reputation: 21

The problem occurs on this line:

m = n.get_mpz_t();

You cannot assign to mpz_t directly, instead use mpz_set():

mpz_set(m, n.get_mpz_t());

So, your code should look like this:

#include <iostream>
#include <gmpxx.h>
using namespace std;

int main (void) {
    mpz_class n;
    n = "12345678901234567890123456789012345678901234567890";
    mpz_t m;
    mpz_init(m);
    mpz_set(m, n.get_mpz_t()); // correct assignment
    gmp_printf("m %Zd\n", m);
}

Upvotes: 2

Related Questions