所以最近我一直在為我正在從事的專案研究 GMP 的內部結構,我遇到了一個對我來說意義不大的構造:(取自 6.2.1 版的標題)
/* For reference, note that the name __mpz_struct gets into C mangled
function names, which means although the "__" suggests an internal, we
must leave this name for binary compatibility. */
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;
#endif /* __GNU_MP__ */
typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */
typedef __mpz_struct mpz_t[1];
在這里的最后一行,我們 typedefmpz_t為一個包含__mpz_structs的大小為 1 的陣列。這對我來說很奇怪,我以前從未見過這樣的建筑。我知道這會導致mpz_t有效地成為指向 an 的指標__mpz_struct,但這是否等效于
typedef __mpz_struct* mpz_t;
有人可以解釋這背后的邏輯嗎?
uj5u.com熱心網友回復:
鑒于typedef __mpz_struct mpz_t[1];,您可以宣告一個實際的mpz_t物件mpz_t foo;。這將為mpz_t.
相反,如果型別是typedef __mpz_struct *mpz_t;,那么mpz_t foo;只會給你一個指標。將沒有空間用于mpz_t. 您必須分配它,然后必須釋放它。所以需要更多的代碼,這會很麻煩。
同時,當將 anmpz_t傳遞給函式時,由于陣列會自動轉換為指標,因此僅傳遞其地址。這允許書寫mpz_add(z, x, y);,這比mpz_add(&z, &x, &y);. 程式員之間可能會爭論,當代碼名義上看起來只是傳遞一個值時,使用型別定義有效地導致對物件的參考傳遞給函式是否容易出錯,但這種風格可能更多適用于使用 GMP 完成的編程型別。
uj5u.com熱心網友回復:
有了這個typedef,像這樣的變數宣告
mpz_t foo;
相當于
__mpz_struct foo[1];
這只會轉換為
__mpz_struct *foo;
如果宣告在函式引數串列中。否則,它是一個普通的陣列宣告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/338878.html
