2013-02-13 100 views
1

假設我有以下類型的結構:如何創建結構數組,其中結構的最後一個元素是一個結構破解

struct employee 
    { 
     int  emp_id; 
     int  name_len; 
     char name[0]; 
    }; 

我知道

struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128); 

相當於到

struct employee 
{ 
    int  emp_id; 
    int  name_len; 
    char name[128]; /* character array of size 128 */ 
}; 

我的問題是我可以創建一個這樣的結構數組,當結構中的最後一個元素是st破壞黑客。

例如:我想創建一個結構employee [3]的數組;使得

僱員[0]可以等同於

struct employee 
    { 
     int  emp_id; 
     int  name_len; 
     char name[128]; /* character array of size 128 */ 
    }; 

僱員[1]可以等同於

struct employee 
    { 
     int  emp_id; 
     int  name_len; 
     char name[256]; /* character array of size 256 */ 
    }; 

僱員[2]可以等同於

struct employee 
    { 
     int  emp_id; 
     int  name_len; 
     char name[512]; /* character array of size 512*/ 
    }; 
+0

以'0'作爲大小的struct hack不符合C.由於C99我們有「靈活的數組成員」,所以它們用'[]'聲明而沒有任何大小。 – 2013-02-13 07:00:53

+0

[在Linux內核代碼中有零元素的數組需要什麼?]可能的重複(http://stackoverflow.com/questions/14643406/whats-the-need-of-array-with-zero-element-in- Linux內核代碼)。這篇文章回答了這個問題,只是忽視了Linux相關的一切。 – Lundin 2013-02-13 07:38:55

回答

4

不,你不能這樣做,因爲各種原因,但你可以創建一個數組,如:

struct employee *all[...]; 

如果你不這樣做,你將需要:

struct employee { 
    ... 
    char *name; 
} 

...您將需要每個name動態分配和分配。

如果仔細考慮,數組中的每個元素必須具有相同的長度。如果不是,它如何被索引?此外,編譯時必須知道這個長度。

但是,如果每個employee元素都是一個指針,那麼您可以使用struct hack來使每個元素具有不同的大小,具體取決於name[]需要多少空間。

+0

對。我會補充說,主要問題之一是,當通過sizeof()計算結構的大小時,該數組將被視爲大小0. http://msdn.microsoft.com/zh-cn/library/b6fae073的.aspx – JBL 2013-02-13 06:33:09

相關問題