If you really have to use c90 then the C FAQ has this covered in Question 2.6 :
struct name {
int namelen;
char namestr[1];
};
struct name *ret =
malloc(sizeof(struct name)-1 + strlen(newname)+1);
/* -1 for initial [1]; +1 for \0 */
Although the FAQ does say:
It's not clear if it's legal or portable, but it is rather popular. An implementation of the technique might look something like this.
Although the gcc
document basically says they support it, in C99 as the FAQ says they added flexible array members, which I cover in this answer which is covered in section 6.7.2.1
Structure and union specifiers and has the following example, which unlike the C90 example does not require special math to account for the size of the array:
EXAMPLE After the declaration:
struct s { int n; double d[]; };
the structure struct s has a flexible array member d. A typical way to use this
is:
int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
and assuming that the call to malloc succeeds, the object pointed to by p
behaves, for most purposes, as if p had been declared as:
struct { int n; double d[m]; } *p;
(there are circumstances in which this equivalence is broken; in particular, the
offsets of member d might not be the same).