柔軟な配列を使用できます。構造体の最後のデータ メンバーである必要があります。
struct person{
int c;
char name[];
};
柔軟な配列を持つ構造体のメモリは、動的に割り当てる必要があります。
C 標準から (6.7.2.1 構造体および共用体指定子)
柔軟な配列メンバーは無視されます。特に、構造体のサイズは、柔軟な配列メンバーが省略された場合と同じですが、省略が意味するよりも多くの末尾のパディングがある場合があります。ただし、. (または ->) 演算子の左側のオペランドが柔軟な配列メンバーを持つ構造体 (へのポインター) であり、右側のオペランドがそのメンバーの名前である場合、そのメンバーが最長の配列 (同じ要素型を持つ) に置き換えられたかのように動作します。 ) アクセスされるオブジェクトよりも構造が大きくなることはありません。配列のオフセットは、置換配列のオフセットと異なる場合でも、柔軟な配列メンバーのオフセットのままです。この配列に要素がない場合、
そして、その使用例があります
20 EXAMPLE 2 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).
または、char へのポインターを宣言して、配列自体のみを動的に割り当てることもできます。
struct person{
int c;
char *name;
};