strlen
原型:size_t strlen( const char *string ); strlenC語言中的一個函數,用于計算字符串的(unsigned int型)長度,不包括’/0’在內。strlen所作的僅僅是一個計數器的工作,它從內存的某個位置(可以是字符串開頭,中間某個位置,甚至是某個不確定的內存區域)開始遍歷,直到碰到第一個字符串結束符’/0’為止,然后返回計數器值。 sizeof sizeof是關鍵字不是函數,sizeof操作符的結果類型是size_t,它在頭文件中typedef為unsigned int類型。
兩者之間的區別與聯系: 1.sizeof是操作符(關鍵字),strlen是函數。 2.sizeof可以用類型做參數,strlen只能用char*做參數,且必須是以”/0”結尾的。 sizeof還可以用函數做參數,比如:
short f() 3.數組做sizeof的參數不退化,傳遞給strlen就退化為指針了。 4.strlen的結果要在運行的時候才能計算出來,是用來計算字符串的長度,不是類型占內存的大小。而sizeof在程序編譯的過程中已經計算出來了。下面我們來看一些有關數組與指針運算的例子:
int a[4]={1,2,3,4};printf("%d/n",sizeof(a)); //16,數組名單獨放在sizeof中代表整個數組大小printf("%d/n",sizeof(a+0); //4,a代表數組首元素的地址printf("%d/n",sizeof(*a));//4,*a代表首元素printf("%d/n",sizeof(a+1));//4,a+1代表第二個元素地址printf("%d/n",sizeof(a[1]));//4,代表第二個元素printf("%d/n",sizeof(&a)); //4,數組的地址,地址的大小在32位平臺為4printf("%d/n",sizeof(&a+1));//4,地址的大小printf("%d/n",sizeof(&a[0]));//4,首元素地址的大小printf("%d/n",sizeof(&a[0]+1));//4,第二個元素的地址printf("%d/n",sizeof(*&a));//16,整個數組大小char a[]={'a','b','c','d','e','f'};printf("%d/n",sizeof(a)); //6數組名單獨放在sizeof中代表整個數組大小printf("%d/n",sizeof(a+0));//4,a代表數組首元素的地址printf("%d/n",sizeof(*a));//1,*a代表首元素printf("%d/n",sizeof(a[1]));//1,代表第二個元素printf("%d/n",sizeof(&a)); //4,數組的地址,地址的大小在32位平臺為4printf("%d/n",sizeof(&a+1));//4,地址的大小printf("%d/n",sizeof(&a[0]+1));//4,第二個元素的地址 printf("%d/n", strlen(a)); //隨機值 printf("%d/n", strlen(a + 0)); //隨機值 printf("%d/n", strlen(*a)); //崩潰 printf("%d/n", strlen(a[1])); //崩潰 printf("%d/n", strlen(&a)); //隨機值 printf("%d/n", strlen(&a + 1)); //隨機值 printf("%d/n", strlen(&a[0] + 1)); //隨機值char *a="abcdef";printf("%d/n",sizeof(a)); //4printf("%d/n",sizeof(a+0));//4printf("%d/n",sizeof(*a));//1,printf("%d/n",sizeof(a[1]));//1,printf("%d/n",sizeof(&a)); //4,printf("%d/n",sizeof(&a+1));//4printf("%d/n",sizeof(&a[0]+1));//4 printf("%d/n", strlen(a)); //6 printf("%d/n", strlen(a + 0)); //6 printf("%d/n", strlen(*a)); //崩潰 printf("%d/n", strlen(a[1])); //崩潰 printf("%d/n", strlen(&a)); //隨機值 printf("%d/n", strlen(&a + 1)); //隨機值 printf("%d/n", strlen(&a[0] + 1)); //隨機值新聞熱點
疑難解答