柔性数组

1
2
3
4
5
6
typedef struct {
int age;
char const *name; // 8 byte,指向外部地址
char intro[]; // 类似指针,但是指向固定的地方(结构体的末尾)
} Person;

如何构建这个结构体呢?

1
2
3
4
5
6
7
8
9
10
11
Person *person(char const *name, int age, char const *intro) {
size_t intro_len = (intro ? strlen(intro) : 0) + 1; // char数组以'\0'结尾
Person *p = (Person *) malloc(sizeof(Person) + intro_len);
p->age = age;
p->name = name;
if (intro) {
strcpy(p->intro, intro);
} else {
p->intro[0]=0;
}
}