繁体   English   中英

如何创建结构数组,其中结构的最后一个元素是结构黑客

[英]How to create an array of structures where the last element of the structure is a struct hack

假设我有以下类型的结构:

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 */
};

我的问题是,当结构中的最后一个元素是struct hack时,我可以创建这样的结构数组。

示例:我想创建一个结构数组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*/
    };

不,你不能这样做,出于各种原因,但你可以做一个像这样的数组:

struct employee *all[...];

如果你不这样做,你将需要:

struct employee {
  ...
  char *name;
}

...并且您将需要动态分配的每个name并分配。

如果你考虑一下,数组中的每个元素必须是相同的长度。 如果没有,它怎么能被索引? 此外,必须在编译时知道该长度。

但是如果每个employee元素都是一个指针,那么你可以使用struct hack使每个元素的大小不同,具体取决于name[]需要多少空间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM