在博文數(shù)據(jù)結(jié)構(gòu)和算法——kd樹中,在構(gòu)建kd樹的過程中,有如下的一段代碼:
#define MAX_LEN 1024typedef struct KDtree{ double data[MAX_LEN]; // 數(shù)據(jù) int dim; // 選擇的維度 struct KDtree *left; // 左子樹 struct KDtree *right; // 右子樹}kdtree_node;在這段代碼中,為了存儲數(shù)據(jù),申請了最大長度為1024的double型數(shù)組。若是數(shù)據(jù)的長度遠遠小于MAX_LEN,這樣的寫法,是及其浪費空間的。
在C語言中,有如下的一種構(gòu)建方法:
struct mumble { //stuff char pc[]; };這種寫法稱為柔性數(shù)組,也叫伸縮性數(shù)組,即變長數(shù)組。即聲明結(jié)構(gòu)體的時候不指定聲明的數(shù)組的大小,等到需要使用的時候根據(jù)具體情況申請足夠大小的空間。
#include <stdio.h>#include <string.h>#include <malloc.h>typedef struct mytest{ int a; double b; int c[];//c不占用空間,只是作為一個符號地址存在,而且必須是結(jié)構(gòu)體的最后一個成員}mt;int main(){ int t[10] = {0,1,2,3,4,5,6,7,8,9}; mt* pmt = (mt*)malloc(sizeof(mt) + sizeof(int)*10 + 1); int i = 0; if (NULL != pmt){ pmt->a = 1; pmt->b = 11; for (i = 0; i < 10; i++){ (pmt->c)[i] = t[i]; } } f注意:柔性數(shù)組只能為結(jié)構(gòu)體的最后一個成員。新聞熱點
疑難解答
圖片精選