零長度數組

在結構體定義中遇到了長度爲 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
相關文章
相關標籤/搜索