#include <stdio.h>
int main(int argc, char *argv[]) {
char s[]="help";
printf("%d",strlen(s));
}
爲什麼上面的輸出是4,是不是5是正確答案?是那個char null終止符包含在長度計數中
它應該是 'H', 'E', 'L', 'P',在存儲器 '\ 0' ..
感謝。
#include <stdio.h>
int main(int argc, char *argv[]) {
char s[]="help";
printf("%d",strlen(s));
}
爲什麼上面的輸出是4,是不是5是正確答案?是那個char null終止符包含在長度計數中
它應該是 'H', 'E', 'L', 'P',在存儲器 '\ 0' ..
感謝。
strlen
:返回給定字節串的長度,不包括空終止符;
char s[]="help";
strlen(s) should return 4.
sizeof
:返回給定字節字符串的長度,包含空終止符;
char s[]="help";
sizeof(s) should return 5.
評論是錯誤的。 'sizeof'返回5:http://pastebin.com/94AbKunk – daaku 2016-11-04 19:03:06
strlen
對元素進行計數直到它到達空字符,在這種情況下它將停止計數。它不會包含它的長度。
這4
的strlen()計算字符數最多,但不包括爲0的值的第一個字符 - 的NUL終止符。
strlen()
不計的字符數在陣列中(事實上,這甚至可能不是可知的(如果你只擁有而不是數組的指針內存)。這樣做,因爲你已發現,數字符,直到但不包括空字符的數目。考慮char s[] = {'h','i','\0','t','h','e','r','e'};
strlen(const char* ptr)
通過計算非零元素開始,直到達到零時返回字符串的長度。所以'\0'
不算數
我建議你參考引用像link這樣的問題。
這顯然表述爲:如果你使用`
A C string is as long as the number of characters between the beginning
of the string and the terminating null character (without including the
terminating null character itself).
的sizeof(S)/的sizeof(char)的'你會得到你所期望的答案。 – 2013-02-16 01:27:35
@WaleedKhan:True - 代碼的寫法如上。不幸的是,看似微不足道的變化(例如'char * s =「help」;')會打破這一點,所以你需要非常小心。只要我們在這裏,'sizeof(char)'被定義爲始終爲1,所以簡單地'sizeof(s)'對於代碼就可以像現在一樣好。 – 2013-02-16 01:45:57
關於這個問題,strlen的文檔不清楚嗎? – 2013-02-16 04:46:59