简体   繁体   English

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

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

Suppose I have a structure of the type below: 假设我有以下类型的结构:

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

I know that 我知道

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

is equivalent to 相当于

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

My question is Can I create an array of such structures when the last element in the structure is struct hack. 我的问题是,当结构中的最后一个元素是struct hack时,我可以创建这样的结构数组。

Example:I want to create a an array of structures employee[3]; 示例:我想创建一个结构数组employee [3]; So that 以便

employee[0] can be equivalent to 员工[0]可以相当于

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

employee[1] can be equivalent to 员工[1]可以相当于

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

employee[2] can be equivalent to 员工[2]可以相当于

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

No, you can't do that, for various reasons, but you could make an array like: 不,你不能这样做,出于各种原因,但你可以做一个像这样的数组:

struct employee *all[...];

If you don't do that, you will need: 如果你不这样做,你将需要:

struct employee {
  ...
  char *name;
}

...and you will need each name allocated dynamically and assigned. ...并且您将需要动态分配的每个name并分配。

If you think about it, every element in an array must be the same length. 如果你考虑一下,数组中的每个元素必须是相同的长度。 If not, how could it be indexed? 如果没有,它怎么能被索引? Furthermore, that length must be known at compile time. 此外,必须在编译时知道该长度。

But if each employee element is a pointer, then you could use the struct hack to make each one a different size, depending on how much space was needed for name[] . 但是如果每个employee元素都是一个指针,那么你可以使用struct hack使每个元素的大小不同,具体取决于name[]需要多少空间。

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

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