可变长数组的实现

以前从来没有用过柔性数组,今天学习一下。
柔性数组也就是指char a[0] 或者 char a[]
基本方式如下

struct type {
  int a;
  int b;
  ~~~~~~
  char a[0];
}

其中a代表的占据的是结构体中的最后一位,本身不占据结构体的空间。
这样可以在运行期中动态分配结构体的大小。
举一个case以备之后使用。

// case 
#include 
using namespace std;

typedef struct type_1 {
    int a;
    char b[0];
} type_1;


typedef struct type_2 {
    int a;
    char b[0];
} type_2;

typedef struct stu {
    string a;
    string b;
} stu;
int main() {
    stu* s = (stu*) malloc(sizeof(stu));
    s->a = "1";
    s->b = "2";
    type_1* p = (type_1*)malloc(sizeof(type_1) + sizeof(stu));
    memcpy(p->b, s, sizeof(stu));
    cout << ((stu*)p->b)->a << endl;
    free(s);
    free(p);
    return 0;
}

你可能感兴趣的:(可变长数组的实现)