【C++基礎編程】#016 計算數組長度:sizeof 運算符介紹

本文首先介紹C++中sizeof運算符的具體用法,再利用sizeof計算數組長度。

sizeof 運算符

sizeof()用於計算C++中數據類型的字節大小,具體應用如下:

#include<iostream>
using namespace std;

int main() {	
	string str = "ab";
	int num = 100;
	cout << sizeof(string) << endl;           //輸出:28
	cout << sizeof(str) << endl;			  //輸出:28
	cout << sizeof(int) << endl;			  //輸出:4
	cout << sizeof(num) << endl;			  //輸出:4
	cout << sizeof(double) << endl;			  //輸出:8
	cout << sizeof(char) << endl;			  //輸出:1

	system("pause");
	return 0;
}

由於數據類型所佔字節大小與個人的電腦有關(本人電腦爲64位),所以輸出結果可能會不同。

計算數組長度

C++中數組長度沒有可以直接用的內置函數進行計算,我們可利用sizeof(),設數組爲array[]

  1. 計算整個數組所佔內存的字節大小sizeof(array)
  2. 計算數值中某個元素所佔內存的字節大小sizeof(array[0])
  3. sizeof(array)/sizeof(array[0])可得到數組長度。

具體應用如下:

#include<iostream>
using namespace std;

int main() {	
	
	int a[3];
	cout << sizeof(a) << endl;                      //輸出:12
	cout << sizeof(a[0]) << endl;					//輸出:4
	cout << sizeof(a) / sizeof(a[0]) << endl;		//輸出:3(數組長度)

	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章