一、概念:柔性数组即数组大小待定的数组
二、原理:结构体中最后一个元素容许是未知大小的数组,故能够由结构体产生柔性数组,但结构中的柔性数组前面必须至少一个其余成员。
三、定义:html
1 struct s_test 2 { 3 int a; 4 double b; 5 float array[]; //或者写成float array[0]; 6 };
0长度的数组在ISO C和C++的规格说明书中是不容许的,会有警告。gcc 为了预先支持C99的这种玩法,不会有警告。数组
四、应用 spa
1 #include <stdio.h> 2 #include <malloc.h> 3 4 void SoftArray(int SoftArrayLength) 5 { 6 int i; 7 typedef struct _soft_array 8 { 9 int len; 10 int array[]; //或者写成:int array[0]; 11 }SoftArray; 12 SoftArray* sa = (SoftArray*)malloc(sizeof(SoftArray) + sizeof(int) * SoftArrayLength); 13 sa->len = SoftArrayLength; 14 for(i=0; i<sa->len; i++) 15 { 16 sa->array[i] = i + 1; 17 } 18 for(i=0; i<sa->len; i++) 19 { 20 printf("%d\n", sa->array[i]); 21 } 22 free(sa); 23 } 24 25 int main() 26 { 27 SoftArray(20); 28 return 0; 29 }
参考博客:http://www.cnblogs.com/Daniel-G/archive/2012/12/02/2798496.htmlcode