簡體   English   中英

大小為 1 的 Typedef(匿名)結構數組

[英]Typedef (anonymous) struct array of size 1

所以最近我一直在為我正在從事的項目研究 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];

在這里的最后一行,我們將mpz_t為一個大小為 1 的數組,其中包含__mpz_struct s。 這對我來說很奇怪,我以前從未見過這樣的建築。 我明白,這導致mpz_t有效是一個指向__mpz_struct ,但是這是相當於或不

typedef __mpz_struct* mpz_t;

有人可以解釋這背后的邏輯嗎?

使用那個typedef ,一個變量聲明像

mpz_t foo;

相當於

__mpz_struct foo[1];

這只會轉換為

__mpz_struct *foo;

如果聲明在函數參數列表中。 否則,它是一個普通的數組聲明。

給定typedef __mpz_struct mpz_t[1]; , 你可以用mpz_t foo;聲明一個實際的mpz_t對象mpz_t foo; . 這將為mpz_t保留內存。

相反,如果類型是typedef __mpz_struct *mpz_t; , 然后mpz_t foo; 只會給你一個指針。 mpz_t將沒有空間。 您必須分配它,然后必須釋放它。 所以需要更多的代碼,這會很麻煩。

同時,當將mpz_t傳遞給函數時,由於數組自動轉換為指針,因此僅傳遞其地址。 這允許編寫mpz_add(z, x, y); ,它比mpz_add(&z, &x, &y);mpz_add(&z, &x, &y); . 程序員之間可能會爭論,當代碼名義上看起來只是傳遞一個值時,使用類型定義有效地導致對對象的引用傳遞給函數是否容易出錯,但這種風格可能更多適用於使用 GMP 完成的編程類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM