柔性数组

本文深入探讨了C++中不确定大小数组的使用技巧,通过一个实例展示了如何设计结构体以灵活地使用不确定大小的数组,并解释了C99标准中关于灵活数组成员的相关规定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

它的基本思想其实可以从一个简单的问题扩展开来,一个空的结构体(类),它的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的时候,这个不完整类型的大小被忽略了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值