柔性数组:在C99定义的结构体中,最后一个元素允许是未知大小(或者是0)的数组,它不占用结构体任何内存,这个数组叫做柔性数组,柔性数组前必须至少有一个其它成员。
使用方式:
#include<stdio.h> #include<string.h> #include<malloc.h> typedef struct _flex_array{ int len; char str; char buff[]; }flex_array; int main(int argc,char **argv) { char *info = "this is a flex array!"; int info_size = strlen(info); printf("info_size:%d,struct size:%d\n",info_size,sizeof(flex_array)); // info_size:21,struct size:8 flex_array *p = (flex_array *)malloc(sizeof(flex_array) + strlen(info)); p->len = info_size; memcpy(p->buff,info,p->len); printf("p:%d,info:%s\n",sizeof(*p),p->buff); // p:8,info:this is a flex array! free(p); return 0; }
时间: 2024-10-13 01:33:41