sizeof與strlen的區(qū)別

先看msdn的官方解釋:

strlen——get the length of a string.
size_t strlen(const char *string);
Each ofthese functions returns the number of characters instring, notincluding the terminating null character.
//函數(shù)返回string里的字符數(shù),不包括終止字符'\0'

sizeof
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or atype (including aggregate types). This keyword returns a value of type size_t.
//返回變量或類型(包括集合類型)存儲空間的大小

When appliedto a structure type or variable,sizeof returns the actual size, whichmay include padding bytes inserted for alignment. When applied to a statically dimensioned array,sizeof returns the size of the entire array. The sizeofoperator cannot return the size of dynamically allocated arrays or externalarrays.
//應用結構體類型或變量的時候,sizeof()返回實際大小,包括為對齊而填充的字節(jié)。當應用到靜態(tài)數(shù)組時,sizeof()返回整個數(shù)組的大小。sizeof()不會返回動態(tài)分配數(shù)組或擴展數(shù)組的大小。

sizeof與strlen有以下區(qū)別:

  • sizeof是一個操作符,而strlen是庫函數(shù)。
  • sizeof的參數(shù)可以是數(shù)據(jù)的類型,也可以是變量,而strlen只能以結尾為'\0'的字符串作參數(shù)。
  • 編譯器在編譯時就計算出了sizeof的結果,而strlen必須在運行時才能計算出來。
  • sizeof計算數(shù)據(jù)類型占內(nèi)存的大小,strlen計算字符串實際長度。

練習

char str[]="hello";
char *p=str;
int n=10;
//請計算
sizeof(str);
sizeof(p);
sizeof(n);
void func(char str[100])
{
    sizeof(str);
}
void *p=malloc(100);
sizeof(p);

答案

char str[]="hello";
char *p=str;
int n=10;
//請計算
sizeof(str);//6,5+1=6,1代表'\0'
sizeof(p);//4,代表指針
sizeof(n);//4,整形占據(jù)的存儲空間
void func(char str[100])
{
    sizeof(str);//4,此時str已經(jīng)轉換為指針了
}
void *p=malloc(100);
sizeof(p);//4,指針大小

sizeof

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 1.在C/C++中實現(xiàn)本地方法 生成C/C++頭文件之后,你就需要寫頭文件對應的本地方法。注意:所有的本地方法的第...
    JayQiu閱讀 2,540評論 0 3
  • Jni數(shù)據(jù)類型 Jni方法 來自 http://blog.chinaunix.net/uid-22028680-i...
    FlyDragonInSky閱讀 1,009評論 0 0
  • 一、(一共三十題) 1.main() { int a[5]={1,2,3,4,5}; int *ptr=(int ...
    iOS_Alex閱讀 1,142評論 0 0
  • 帶著強烈預感入夢,仍舊重復昨天的夢境。 七月夏日的高空,云朵大朵連綿,厚厚重重遮掩。自身依舊變幻。 我仿佛參與者,...
    憑你矣閱讀 249評論 0 0
  • 想念,我的 都是從夜深開始 北京的天 偶爾會看見月亮 今天沒有 我第一個愛的人 第一個為我正領子的人 不是同一人 ...
    江宥祀閱讀 185評論 0 0

友情鏈接更多精彩內(nèi)容