为什么不对 C 样式字符串进行空指针检查?
Why isn't working null pointer check for C style string?
这是我的功能:
void printCString(char *s)
{
while (s != nullptr) // printing doesn't stop after ! from passed string.
{
std::cout << *s;
++s;
}
}
我称之为:
char s[]{ "Hello, world!" };
printCString(s);
如果我将 while
块中的停止条件替换为:
while (*s != '[=12=]')
比它运作良好。谁能解释一下为什么会出现这种行为?
s
永远不会是 nullptr
,因为 nullptr
无法通过指针算法获得。
从概念上讲,您需要 遵从 s
,但 *s != nullptr
无法编译。这不是坏事,因为不能保证 nullptr
与 C 风格的字符串终止符 NUL
.
相同
这是我的功能:
void printCString(char *s)
{
while (s != nullptr) // printing doesn't stop after ! from passed string.
{
std::cout << *s;
++s;
}
}
我称之为:
char s[]{ "Hello, world!" };
printCString(s);
如果我将 while
块中的停止条件替换为:
while (*s != '[=12=]')
比它运作良好。谁能解释一下为什么会出现这种行为?
s
永远不会是 nullptr
,因为 nullptr
无法通过指针算法获得。
从概念上讲,您需要 遵从 s
,但 *s != nullptr
无法编译。这不是坏事,因为不能保证 nullptr
与 C 风格的字符串终止符 NUL
.