1. 程式人生 > >sizeof運算子來獲取各種資料型別在記憶體中所佔位元組數--gyy整理

sizeof運算子來獲取各種資料型別在記憶體中所佔位元組數--gyy整理

C++並沒有規定各種資料型別在記憶體中的儲存大小,依賴於不同的編譯器的不同而不同,要想獲知當前編譯器對各種資料型別分配的大小,可以通過sizeof運算子來獲取。

使用方法1:

sizeof(資料型別)  

使用方法2:

sizeof(變數名   或 常量名 或 表示式  )

sizeof(int)     

int  a;

sizeof(a)

//資料型別空間分配情況
#include <iostream>
using namespace std;
int main()
{  
   cout<<"vc++6.0 編譯環境下,各種資料型別變數所佔的記憶體空間大小(位元組為單位)"<<endl;
   cout<<"sizeof(int)  "<<sizeof(int)<<endl;
   cout<<"sizeof(short int)  "<<sizeof(short)<<endl;
   cout<<"sizeof(long int)  "<<sizeof(long)<<endl;
   cout<<"sizeof(unsigned int)  "<<sizeof(unsigned)<<endl;
   cout<<"sizeof(unsigned short int)  "<<sizeof(unsigned short)<<endl;
   cout<<"sizeof(unsigned long int)  "<<sizeof(unsigned long)<<endl;
   cout<<"sizeof(char )  "<<sizeof(char)<<endl;
   cout<<"sizeof(float)  "<<sizeof(float)<<endl;
   cout<<"sizeof(double)  "<<sizeof(double)<<endl;
   cout<<"sizeof(long double)  "<<sizeof(long double)<<endl;
   return 0;
}
執行結果