我正在通過Bjarne Stroustrup的閱讀C++的一個示例,我很難理解一個早期的示例。在下面的代碼中,while循環用於將指針遞增到C樣式字符串,直到它遇到空字符。我沒有得到的是爲什麼指向一個空字符會導致指針採取nullptr的值。它似乎應該是一個非常好的指針,恰好指向一個空值。我會感到驚訝,如果它是一個作家錯誤,因爲這本書包含在這裏stackexchange的reccommendations:The Definitive C++ Book Guide and List通過指針遞增來遍歷C字符串
int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
for (; p!=nullptr; ++p)
if (∗p==x)
++count;
return count;
}
它不會;該代碼示例是錯誤的 – 2014-10-07 05:51:49
本書中的示例不同。循環是'while(* p)'。你有哪個版本? – imreal 2014-10-07 05:56:01
那麼,我有一個版本,我發現通過谷歌搜索「* C++ * pdf遊覽」(第一個結果)。我猜對了,儘管有趣,但它聲稱會被複制到2014. – agd 2014-10-07 06:03:09