Janis F
Janis F

Reputation: 2630

How do I manage an array of mpz_t

I'm using GMP and I need an array of mpz_t. sizeof(mpz_t) gives 16, but the numbers I'm storing are considerably larger than that. Does mpz_t grow "in place", i. e. do I need to allocate more memory and allow for growth in-place, or does GMP allocate the space for them elsewhere and just keep references (in which case, I'm assuming, I won't have to take any special precautions.)

Upvotes: 5

Views: 3969

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409136

Think of it like this: if you declare a single mtz_t variable, the space for that variable is statically allocated by the compiler at the time of compilation. How could the size of the variable possibly change during run-time? It can't, which means that using it in an array is perfectly fine.

Upvotes: 3

dhke
dhke

Reputation: 15388

Yes, you can declare an array of mpz_t. It's explicitly mentioned in the GMP info pages:

mpz_t vec[20];

If you look into the header file, mpz_t holds a pointer (_mp_d) to an array of "limbs" that is allocated and resized dynamically via the usual means.

As for weirdness, of course:

typedef __mpz_struct mpz_t[1];

In GMP 5.1.3, an mpz_t is a one-element array of __mpz_struct, so that declaring an element works as usual. However, only a pointer gets passed to function calls. Nice trick, actually.

Upvotes: 5

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

From the GNU MP 3.11 manual the following lines are relevant.

GMP variables are small, containing only a couple of sizes, and pointers to allocated data. Once you have initialized a GMP variable, you don't need to worry about space allocation. All functions in GMP automatically allocate additional space when a variable does not already have enough. They do not, however, reduce the space when a smaller value is stored.

So, I guess that answers your question.

Upvotes: 3

autistic
autistic

Reputation: 15632

It is safe to declare an array to store a number of mpz_t values. According to the GNU MP manual:

mpz_t is actually implemented as a one-element array of a certain structure type. This is why using it to declare a variable gives an object with the fields GMP needs, but then using it as a parameter passes a pointer to the object. Note that the actual contents of an mpz_t are for internal use only and you should not access them directly if you want your code to be compatible with future GMP releases.

Upvotes: 5

Related Questions