C語言中sizeof和strlen的區別與聯繫
在學習C語言的時候發現經常將sizeof和strlen弄混淆,今天有遇到這個問題,所以查了一些資料,將他們總結在下面,雖然不是很全,但已經可以通過他們之間的比較來區開分了
strlen:一般用來統計字符串中字符的個數
sizeof:一般統計對象所佔的單元(字節)的個數,一般來說,般以8位二進制作爲一個存儲單元,所以字節數一般等於存儲單元的個數。
sizeof與strlen比較
比較項目
sizeof
strlen
返回值
整數
整數
參數
類型、數組、指針‘函數
數組
是否包含“\0”
包含
不包含(以“\0結束”)
本質
運算符
函數
計算時間
編譯
運行
一般用途
統計存儲單元個數
統計字符串中字符的個數,包括空格
sizeof用法注意:1、用於測定類型所佔存儲單元時,類型必須用sizeof(類型)
2、用於數組時,表示數組所佔的存儲空間的大小,可以不用(),即:sizeof(name) = sizeof name,name爲數組
#include <stdio.h>
#include <string.h>
#define PRAISE "What a super marvelous name!"
int main(void)
{
char name[40];
printf("What's your name?\n");
scanf("%s",name);
printf("Hello,%s.%s\n",name,PRAISE);
printf("Your name of %d letters occupies %d memory cells.\n",strlen(name),sizeof(name));
printf("The phrase of praise has %d letters",strlen(PRAISE));
printf("and occupies %d cells.\n",sizeof(PRAISE));
return 0;
}
上面爲C Primer Plus上的一段示例代碼可以比較出他們的不同之處
int sum(int ar[], int n)
{
int i;
int total = 0;
for(i=0;i<n;i++)
{
total += ar[i];
}
printf("The size of ar is %zd bytes.\n",sizeof ar);
return total;
}
注意:sizeof後面的對象如果是實參數組名,則結果爲該數組的存儲空間,但sizeof如果爲一個指向數組首元素的指針,則對於4字節地址的計算機系統,指針的大小爲4字節
如以上的sum函數,ar是一個指向數組的首元素的指針,所以該函數輸出的結果爲4。