一 示例代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct name {
int name_len;
char name_val[1];
};
struct name *make_name(const char *new_name) {
// 分配name并且除去name_val所占字节 在加上'\0'所占字节
int len = strlen(new_name);
struct name *ret = (struct name *)malloc(sizeof(struct name) - 1 + len + 1);
if (!ret) {
return NULL;
}
ret->name_len = len;
strcpy(ret->name_val, new_name);
ret->name_val[len] = 0; // 将'\0'放置最后
return ret;
}
int main() {
struct name *my_name = make_name("hello world c language...!");
if (!my_name) {
printf("alloc failed.\n");
return -1;
}
printf("name len:%d\n", my_name->name_len);
printf("name val:%s\n", my_name->name_val);
free(my_name);
return 0;
}
二 代码简述
1.struct name使用name_val存储字符串,但name_val只占1个字节,这确实让人疑惑;
2.struct name中的name_len表明字符串的字节数;
3.当生存一个新的字符串时,实例采用malloc方式,因此my_name是占用包含字符串本身一段连续存储;
4.这种技巧只适用在堆上分配字符串空间。