一、概念:柔性數組即數組大小待定的數組
二、原理:結構體中最後一個元素容許是未知大小的數組,故能夠由結構體產生柔性數組,但結構中的柔性數組前面必須至少一個其餘成員。
三、定義: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