现在的位置: 首页 > 综合 > 正文

结构体零长数组的妙用

2019年04月21日 ⁄ 综合 ⁄ 共 1351字 ⁄ 字号 评论关闭
// 零长数组:用于结构体的末尾,本身不占用空间,因此对sizeof没有影响,但有利于实现可变程度的数组
// 如果有点编译器不支持,为了通用型,可以换成1长数组

#include <stdio.h>
#include <stdlib.h>


// 结构体定义
struct Item1 
{
	int type;
	int len;
	unsigned char data[0];
	// 或: // unsigned char data[];
};

int main()
{
	//1
	//struct Item1 in1;
	//printf("sizeof(in1): %d\n",sizeof(in1));

	//2
	//char ca1[100];
	//struct Item1 *it1;
	//int i;
	//it1=(struct Item1 *)ca1;
	//it1->type=10;
	//it1->len=92;
	//for (i=0; i<it1->len; i++)
	//{
	//	it1->data[i]=i*i;
	//}


	//3
	struct Item1 *it2 = (struct Item1 *)malloc( sizeof(struct Item1) +100 );
	int i;
	for (i=0; i<100; i++)
	{
		it2->data[i] = i*2;
	}

	for (i=0; i<100; i++)
	{
		printf("%d - %d\n", i, it2->data[i]);
	}

	free(it2);

	return 0;
}

 

 

 

C++:

#include<iostream>

using namespace std;
// 结构体定义
struct Item1 
{
	int type;
	int len;
	int data[0];
	// 或: // unsigned char data[];
};

int main()
{
	
	
	struct Item1 *it2 = (struct Item1 *)new char[ sizeof(struct Item1) + sizeof(int)*100 ];
	int i;
	for (i=0; i<100; i++)
	{
		it2->data[i] = i*i;
	}

	for (i=0; i<100; i++)
	{
		printf("%d - %d\n", i, it2->data[i]);
	}

	delete it2;

	return 0;
} 

 

出现警告,仍可运行:

>e:\求职\zero_array\zero_array\main.cpp(13) : warning C4200: 使用了非标准扩展 : 结构/联合中的零大小数组
1>        当 UDT 包含大小为零的数组时,无法生成复制构造函数或副本赋值运算符

变通的方法是,采用1长度:

#include<iostream>

using namespace std;
// 结构体定义
struct Item1 
{
	int type;
	int len;
	int data[1];
	// 或: // unsigned char data[];
};

int main()
{
	
	
	struct Item1 *it2 = (struct Item1 *)new char[ sizeof(struct Item1) + sizeof(int)*(100-1) ];
	int i;
	for (i=0; i<100; i++)
	{
		it2->data[i] = i*i;
	}

	for (i=0; i<100; i++)
	{
		printf("%d - %d\n", i, it2->data[i]);
	}

	delete it2;

	return 0;
} 

 

抱歉!评论已关闭.