零长度数组

在结构体定义中遇到了长度为 0 的数组,它的做用是什么呢?写下面的代码进行测试。ios

代码

#include <iostream>
using namespace std;

struct Info
{
	int num;
	char zero_array[0];
};

int main()
{
	struct Info info;
	cout << "Struct Start Address:" << &info << endl;
	cout << "Struct End Address:" << &info.zero_array << endl;
	return 0;
}

结果为数组

Struct Start Address:0x7fff87553bf0
Struct End Address:0x7fff87553bf4

End Address 恰好比 Start Address 多出一个 int 的长度。测试

它能够指示结构体结束时的地址。spa

做用

咱们能够动态地在 Info 结构体中扩充内容code

int main()
{
	struct Info info;
	cout << "Struct Start Address:" << &info << endl;
	cout << "Struct End Address:" << &info.zero_array << endl;
	
	info.zero_array[0] = 't';
	info.zero_array[1] = 'i';
	info.zero_array[2] = 't';
	info.zero_array[3] = 'u';
	info.zero_array[4] = 's';

	cout << "content: " << info.zero_array << endl; 
	
	return 0;
}

打印it

Struct Start Address:0x7fff72d5db70
Struct End Address:0x7fff72d5db74
content: titus
相关文章
相关标签/搜索