先看一個例子:
#include <string.h>
#include <stdio.h>
int main()
{
char buf[] = {1, 2, 0, 2, 3, 4, 5, 6, 7};
char *p = buf;
char *temp = "12345";
char *temp1 = "12345\r\n";
printf("temp sizeof:%d\r\ntemp1 sizeof:%d\r\n", sizeof(temp), sizeof(temp1));
printf("temp strlen:%d\r\ntemp1 strlen:%d\r\n", strlen(temp), strlen(temp1));
printf("p strlen:%d\r\np sizeof:%d\r\n", strlen(p), sizeof(p));
return 0;
}
輸出的結(jié)果如下:
temp sizeof:8
temp1 sizeof:8
temp strlen:5
temp1 strlen:7
p strlen:2
p sizeof:8
分析:
strlen 是一個函數(shù),它用來計算指定字符串 str 的長度,但不包括結(jié)束字符(即 null 字符)
關(guān)鍵字 sizeof 是一個單目運算符,而不是一個函數(shù)。與函數(shù) strlen 不同,它的參數(shù)可以是數(shù)組、指針、類型、對象、函數(shù)等
指針p的使用strlen函數(shù)的話遇到'\0'就會結(jié)束這個函數(shù),意思以為指針p中只有兩位數(shù),指針p使用sizeof的情況是64位的話是8,如果是32位的話是4;