1

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.

Example:I want to create a an array of structures employee[3]; So that

employee[0] can be equivalent to

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

employee[1] can be equivalent to

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

employee[2] can be equivalent to

struct employee
    {
        int     emp_id;
        int     name_len;
        char    name[512]; /* character array of size 512*/
    };
Kranthi Kumar
  • 1,184
  • 3
  • 13
  • 26
  • The struct hack with `0` as a size is not conforming to C. Since C99 we have "flexible array members", they are declared with `[]` without any size. – Jens Gustedt Feb 13 '13 at 07:00
  • Possible duplicate of [What's the need of array with zero element in Linux kernel code?](http://stackoverflow.com/questions/14643406/whats-the-need-of-array-with-zero-element-in-linux-kernel-code). That post answers the question, just disregard everything Linux-related. – Lundin Feb 13 '13 at 07:38

1 Answers1

4

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.

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[].

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329