nullptr用于终止C风格的字符串吗?

时间:2016-06-17 22:49:01

标签: c++ c pointers c++11 c-strings

我对来自 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; 
}
// The definition of count_x() assumes that the char* is a C-style string,
// that is, that the pointer points to a zero-terminated array of char.

我知道如果p未分配,count_x应该终止,并且for循环应该在到达p引用的C风格字符串的末尾时终止。

但是,当我构建一个使用count_x()的main函数时,它似乎永远不会正确终止:

int main () {

    char teststring[] = {'b', 'l', 'a', 'h', '\0'}; 
    cout << "teststring is: " << teststring << endl; 
    cout << "Number of b's is: " << count_x(teststring, 'b') << endl; 

    return 0;  
}

执行此操作会打印大量垃圾,然后以分段错误退出。如果我将for (; p!=nullptr; ++p)中的count_x替换为for (; *p!='\0'; ++p),则会正确执行。我想这意味着字符串没有正确终止。如果是这样,我如何终止C风格的字符串,以便可以在这里使用nullptr?

编辑:评论中的讨论已经澄清了这种情况。我正在使用2013年9月出版的第一本书,上面的内容是错误打印的。本书从2015年1月开始的第三版(在评论中链接)具有使用for (; *p!=0; ++p)代替for (; p!=nullptr; ++p)的更正示例。此修正也记录在本书的勘误表中。谢谢!

Edit2:对不起,伙计们,这显然已经在早些时候在这里问过:Buggy code in "A Tour of C++" or non-compliant compiler?

1 个答案:

答案 0 :(得分:12)

不,NULL指针不用于终止字符串。使用NUL字符。它们是不同的东西,但是如果你将它们中的任何一个分配给C中的整数,结果总是相同的:零(0)。

NUL字符在C中表示为'\0',占用一char个存储空间。 NULL指针在C中表示为0,并占用与void *相同的存储空间。例如,在64位计算机上,void *为8个字节,而'\0'为1个字节。

即,nullptr与'\0'不同。并且该字符是空字符,称为NUL,但它不应被称为NULL字节或NULL字符。