【发布时间】:2017-12-16 12:00:30
【问题描述】:
目前我正在阅读 Byarne Stroustrup 的“C++ 之旅”。重要的是:关于“指针、数组和引用”,他举了一个关于使用nullptr 的例子:
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;
}
在我的主目录中:
int main(){
char* str = "Good morning!";
char c = 'o';
std::cout << count_x(str, c) << std::endl;
return 0;
}
当我运行程序崩溃时,我在行抛出异常
if (*p == x)
如果我把循环改成这样:
for (; *p; p++)
if (*p == x)
++count;
现在一切正常!我正在使用 MSVC++ 14.0。
- 我在
ideone上运行的相同代码我没有遇到异常,但结果始终是0,应该是3:
【问题讨论】:
-
@DeiDei:是的,我刚刚复制并粘贴了代码。我添加的是主要代码。
-
@DeiDei:这应该如何正确:
*p != nullptr?我猜nullptr仅适用于地址指针指向的地址,而不是它们指向的地址中的值。 -
我在“C++ 之旅”的任何勘误表中都没有找到这个。你应该写信给 Bjarne 让他知道。这是一个错误。
-
来自online version 的代码使用正确的检查 - 你从哪里复制代码?
-
顺便说一句,
char* str = "Good morning!";不是有效的 C++ 代码。str应该是const char*类型。 MSVC++ 太宽松了。