先看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,指針大小