C Primer Plus總結:
1.不同點
sizeof運算符是以位元組為機關傳回運算符對象的大小;
strlen()函數給出字元串中的字元長度;
2.相同點
sizeof運算符和strlen()函數傳回類型可以用%zd轉換(不識别%zd,嘗試換成%u或者%lu)
sizeof運算符和strlen()函數傳回的實際類型是unsigned或者unsigned long
此例用C Primer Plus 程式舉例它們的不同點
#include<stdio.h>
#include<string.h> //提供strlen()函數的原型
#define PRAISE "You are an extraordinary being."
int main(void)
{
char name[40];
printf("What's your name? ");
scanf("%s",name);
printf("Hello, %s. %s\n",name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n",strlen(name),sizeof name);
printf("The phrase of praise has %zd letters ",strlen(PRAISE));
printf("and occupies %zd memory cells.\n",sizeof PRAISE);
return 0;
}
程式輸出結果如下:
總結:
第一個printf()函數輸出What’s your name?;
第二個printf()函數輸出字元串nameSerendipity,PRAISE;
第三個printf()函數輸出name字元串字元長度11,name位元組大小為40;
第四個printf()函數輸出PRAISE字元串長度為31;
第五個printf()函數輸出PRAISE位元組大小為32;
綜上所述:strlen()函數給出的字元串的字元長度包括空格和标點符号,第三個printf()函數name數組第12個單元存儲空字元,但是strlen()函數沒有把空字元計算其中,是以結果為11;