妙用0元素数组 实现大小可变结构体

妙用0元素数组 实现大小可变结构体

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct aa{ 
    int a;
    int b;
};

struct bb{ 
    struct aa test[0];
}; 数组

int main(void)
{
    struct bb *p=(struct bb*)malloc(sizeof(struct bb)+sizeof(struct aa)*100);
    p->test[0].a=10;
    p->test[0].b=20;
    printf("%d,%d\n",p->test[0].a,p->test[0].b);
    return 0;
} ide

看这个结构体的定义:
typedef struct st_type
{
     int nCnt;
     int item[0];
}type_a;
(有些编译器会报错没法编译能够改为:)
typedef struct st_type
{
     int nCnt;
     int item[];
}type_a;
    这样咱们就能够定义一个可变长的结构,用sizeof(type_a)获得的只有4,就是sizeof(nCnt)=sizeof(int)那个0个元素的数组没有占用空间,然后咱们能够进行变长操做了。
        C语言版:        type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
        C++语言版:        type_a *p = (type_a*)new char[sizeof(type_a)+100*sizeof(int)];
    这样咱们就产生了一个长为100的type_a类型的东西用p->item[n]就能简单地访问可变长元素,原理十分简单,分配了比sizeof(type_a)多的内存后int item[];就有了其意义了,它指向的是int nCnt;后面的内容,是没有内存须要的,而在分配时多分配的内存就能够由其来操控,是个十分好用的技巧。
而释放一样简单:
        C语言版:free(p);
        C++语言版:delete []p;
    这个被称为灵活/弹性数组成员(fleible array member)C89不支持这种东西,C99把它做为一种特例加入了标准。可是,C99所支持的是incomplete type,而不是zero array,形同int item[0];这种形式是非法的,C99支持的形式是形同int item[];只不过有些编译器把int item[0];做为非标准扩展来支持,并且在C99发布以前已经有了这种非标准扩展了,C99发布以后,有些编译器把二者合而为一。 flex


    下面是C99中的相关内容:
6.7.2.1 Structure and union specifiers
    As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. With two exceptions, the flexible array member is ignored. First, the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length.106) Second, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it. this

注意区分 C99新增的“可变长数组”:
C89 标准规定,数组大小必须是在编译时刻肯定的;在C99 中,这个标准项被扩展,能够是运行时刻肯定的值。也就是说, 可变长数组和 C++ 自己没有关系,只要是支持 C99 的就能够使用可变长数组,包括支持 C99 的 C 编译器。 内存

须要注意的是,可变长数组的维数在数组生存期内是不变的,也就是说,可变长数组不是动态的,可变的只是数组的大小。 ci

引进这一特性的目的是为了支持数值处理。 element

相关文章
相关标签/搜索