在结构体定义中遇到了长度为 0 的数组,它的作用是什么呢?写下面的代码进行测试。
代码
#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 的长度。
它可以指示结构体结束时的地址。
作用
我们可以动态地在 Info 结构体中扩充内容
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;
}
打印
Struct Start Address:0x7fff72d5db70
Struct End Address:0x7fff72d5db74
content: titus
来源:oschina
链接:https://my.oschina.net/u/1420197/blog/812116