天天看點

sizeof運算符和strlen()函數作用于c、c++風格字元串

說明:

1、strlen()函數:

以下來自cplusplus.com:

size_t strlen ( const char * str );

Get string length

Returns the length of the C string str.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

This should not be confused with the size of the array that holds the string. For example:

char mystr[]="test string"; 
           

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

In C++, char_traits::length implements the same behavior.

strlen(…)是函數,要在運作時才能計算。參數必須是字元型指針 const char*(char*能轉換為const char*)。當數組名作為參數傳入時,實際上數組就退化成指針了。

它的功能是:傳回字元串的長度。該字元串可能是自己定義的,也可能是記憶體中随機的,該函數實際完成的功能是從代表該字元串的第一個位址開始周遊,直到遇到結束符NULL。傳回的長度大小不包括NULL。

2、sizeof(…)是運算符,vs2015中typedef為unsigned long long,其值在編譯時即計算好了,參數可以是數組、指針、類型、對象、函數等。

它的功能是:獲得保證能容納實作所建立的最大對象的位元組大小。由于在編譯時計算,是以sizeof不能用來傳回動态配置設定的記憶體空間的大小。實際上,用sizeof來傳回類型以及靜态配置設定的對象、結構或數組所占的空間,傳回值跟對象、結構、數組所存儲的内容沒有關系。

具體而言,當參數分别如下時,sizeof傳回的值表示的含義如下:

  • 數組——編譯時配置設定的數組空間大小;
  • 指針——存儲該指針所用的空間大小(存儲該指針的位址的長度,是長整型,32位系統應該為4,64位系統為8);
  • 類型——該類型所占的空間大小;
  • 對象——對象的實際占用空間大小;
  • 函數——函數的傳回類型所占的空間大小。函數的傳回類型不能是void。

執行個體:

string s("hiyo");
    char cstring[] = "hiyo";
    const char* cs = "hiyo";

    cout << strlen(s.c_str()) << endl; //c_str()傳回指向c風格字元串的指針
    cout << s.size() << endl;  //string類size()接口
    cout << sizeof(s) << endl; //string類對象的大小,與具體内容無關,與具體實作有關,這是vs2015下 
    cout << sizeof(s.c_str()) << endl; //指針變量本身大小
    cout << strlen(cstring) << endl;//字元串自身長度
    cout << sizeof(cstring) << endl;//字元數組大小,包含隐藏的空字元
    cout << strlen(cs) << endl;//字元串自身大小
    cout << sizeof(cs) << endl;//指針大小
           

運作結果:

sizeof運算符和strlen()函數作用于c、c++風格字元串

繼續閱讀