Go to the previous, next section.


Before you can use a variable or object of type MP_INT or MP_RAT, you must initialize it. This fills in the components that point to dynamically allocated space for the limbs of the number.

When you are finished using the object, you should clear out the object. This frees the dynamic space that it points to, so the space can be used again.

Once you have initialized the object, you need not be concerned about allocating additional space. The functions in the MP package automatically allocate additional space when the object does not already have enough space. They do not, however, reduce the space in use when a smaller number is stored in the object. Most of the time, this policy is best, since it avoids frequent re-allocation. If you want to reduce the space in an object to the minimum needed, you can do _mpz_realloc (&object, mpz_size (&object)).

The functions to initialize numbers are mpz_init (for MP_INT) and mpq_init (for MP_RAT).

mpz_init allocates space for the limbs, and stores a pointer to that space in the MP_INT object. It also stores the value 0 in the object.

In the same manner, mpq_init allocates space for the numerator and denominator limbs, and stores pointers to these spaces in the MP_RAT object.

To clear out a number object, use mpz_clear and mpq_clear, respectively.

Here is an example of use:

  MP_INT temp;
  mpz_init (&temp);

  ... store and read values in temp zero or more times ...

  mpz_clear (&temp):

You might be tempted to copy an integer from one object to another like this:

MP_INT x, y;

x = y;

Although valid C, this is an error. Rather than copying the integer value from y to x it will make the two variables share storage. Subsequent assignments to one variable would change the other mysteriously. And if you were to clear out both variables subsequently, you would confuse malloc and cause your program to crash.

To copy the value properly, you must use the function mpz_set. (see section Integer Assignment Functions)

Go to the previous, next section.