looking at the source code of GMPlib (the Gnu library for multy-precision calculations) I found this kind of code for building its mp*_t structures. And I have replicated it in various other works I have done, but I don’t fully understand it.
typedef struct
{
int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the _mp_d field. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
I understand that this defines the ‘shape’ of a structure with two integers and a mp_limb_t and typedefs it to __mpz_struct
Then comes this line:
typedef __mpz_struct mpz_t[1];
And after a while, this other one:
typedef __mpz_struct *mpz_ptr;
I understand that the second one is typedefining __mpz_struct * to mpz_ptr (Which is used in the function prototypes)
But I don’t understand what the first one does and why it works so I can declare a mpz_t. Can anyone explain why it works?
Thanks!
The simplest way to understand a
typedefis the rule Define it like you use it. In other words, when you declare atypedefyou’re making a new name, but should you remove thetypedefkeyword you’ll get an object of the aliased type.For example:
This makes a new type name, called “mpz_t”. But if we rewrite:
we immediately understand it makes an array of whatever
__mpz_structis. So now we know what the new typempz_t adoes: it makes an array of__mpz_structwith one element.