柔性数组的定义很使用
#includestdio.h#includestdlib.hstructs//结构体不能在定义时初始化{inta;intarr[];};intmain(){structs*p(structs*)malloc(sizeof(structs)5*sizeof(int));//为arr[]在堆区开辟20个字节if(pNULL){printf(malloc失败\n);return1;}(*p).a100;//等价写法 p-a100;//使用柔性数组for(inti0;i5;i){(*p).arr[i]i1;}for(inti0;i5;i){//printf(%d , (*p).arr[i]);}/*free(p); p NULL;*///扩展柔性数组structs*p1(structs*)realloc(p,sizeof(structs)10*sizeof(int));//扩展的地址就是柔性数组部分if(p1NULL){printf(realloc失败\n);free(p);pNULL;return1;}pp1;for(inti0;i10;i){(*p).arr[i]i1;}for(inti0;i10;i){printf(%d ,(*p).arr[i]);}free(p1);p1NULL;pNULL;return0;}
上一篇/下一篇内容由系统自动关联
返回资讯列表 →