假設我有以下類型的結構:如何創建結構數組,其中結構的最後一個元素是一個結構破解
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'作爲大小的struct hack不符合C.由於C99我們有「靈活的數組成員」,所以它們用'[]'聲明而沒有任何大小。 – 2013-02-13 07:00:53
[在Linux內核代碼中有零元素的數組需要什麼?]可能的重複(http://stackoverflow.com/questions/14643406/whats-the-need-of-array-with-zero-element-in- Linux內核代碼)。這篇文章回答了這個問題,只是忽視了Linux相關的一切。 – Lundin 2013-02-13 07:38:55