首页 > 编程 > C++ > 正文

C/C++学习笔记——柔性数组

2019-11-08 18:30:41
字体:
来源:转载
供稿:网友

1、问题来源

在博文数据结构和算法——kd树中,在构建kd树的过程中,有如下的一段代码:

#define MAX_LEN 1024typedef struct KDtree{ double data[MAX_LEN]; // 数据 int dim; // 选择的维度 struct KDtree *left; // 左子树 struct KDtree *right; // 右子树}kdtree_node;

在这段代码中,为了存储数据,申请了最大长度为1024的double型数组。若是数据的长度远远小于MAX_LEN,这样的写法,是及其浪费空间的。

2、解决的方法

在C语言中,有如下的一种构建方法:

struct mumble { //stuff     char pc[]; };

这种写法称为柔性数组,也叫伸缩性数组,即变长数组。即声明结构体的时候不指定声明的数组的大小,等到需要使用的时候根据具体情况申请足够大小的空间。

#include <stdio.h>#include <string.h>#include <malloc.h>typedef struct mytest{ int a; double b; int c[];//c不占用空间,只是作为一个符号地址存在,而且必须是结构体的最后一个成员}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]; } } fPRintf(stderr, "mt->:a:%d;b:%lf/n", pmt->a, pmt->b); for (i = 0; i < 10; i++){ fprintf(stderr, "%d/n", (pmt->c)[i]); } return 0;}

注意:柔性数组只能为结构体的最后一个成员。

参考文献

柔性数组-读《深度探索C++对象模型》有感
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选