柔性数组

来源:互联网 发布:游族网络经常加班 编辑:程序博客网 时间:2024/04/25 09:49

它的基本思想其实可以从一个简单的问题扩展开来,一个空的结构体(类),它的size是多少?稍微有点编程经验的人都会说是1,因为虽然他没有实际的内容,这个1起到了占位的作用。

下面我们要面对这么一个问题,对于一个结构体,它有一个数组成员,但是数组的大小却不确定,那么应该怎么设计这个结构体呢?我们先给出一个测试代码:

struct Test{int size;//int arr[];//两种方法均可int arr[0];};int main(){printf("%d\n",sizeof(Test));int len = 10;Test* pTest = (Test*)malloc(sizeof(Test) + len * sizeof(int));pTest->size = len;for(int i = 0; i < len; ++i)pTest->arr[i] = i;for(int i = 0; i < pTest->size;++i)printf("%d\n",pTest->arr[i]);printf("%d\n",sizeof(Test));printf("%d\n",sizeof(*pTest));delete pTest;return 0;}


可以看到,结构体中有一个长度为0或者长度省略的数组,它的作用也相当于“占位”。当我们实际使用时,我们可以对这个数组进行动态的扩展。


下面是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 elementtype) 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.


简单的说,有几点需要注意:

1.这个长度不定的数组必须放在最后,不能放在前面。如果放在前面,编译器会报错。这是显而易见的,因为一个“ incomplete array type”是用来占位的,如果不知道占几位的话,后面其他成员的地址就无法确定了。

2.当求size的时候,这个不完整类型的大小被忽略了。