您可以使用灵活的数组。它必须是结构的最后一个数据成员。
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;
};