【问题标题】:Is nullptr used to terminate C-style strings?nullptr 是否用于终止 C 风格的字符串?
【发布时间】:2016-06-21 01:29:34
【问题描述】:

我对 A Tour of 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 应该终止,并且当它到达 p 引用的 C 样式字符串的末尾时,for 循环应该终止。

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

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!='\0'; ++p) 替换count_x 中的for (; p!=nullptr; ++p),它会正确执行。我猜这意味着字符串没有正确终止。如果是这样,我如何终止 C 风格的字符串,以便可以在这里使用 nullptr?

编辑:在 cmets 中有一个讨论澄清了这种情况。我使用的是 2013 年 9 月以来这本书的第一次印刷,上面的印刷有误。从 2015 年 1 月开始的第三版(链接在 cmets 中)有更正的示例,它使用 for (; *p!=0; ++p) 而不是 for (; p!=nullptr; ++p)。该更正也记录在本书的勘误表中。谢谢!

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

【问题讨论】:

  • 您发布的count_x 功能已损坏。 nullptr 不能那样工作。
  • 该代码已损坏。忽略它。他们可能是指for (; *p != 0; ++p)
  • 本书seems to use a while loop。你用的是什么版本?
  • @imallett:上一页,还有一个带有for 循环的版本,但该版本使用正确的测试而不是与nullptr 进行比较。
  • 勘误表中可能有错误,或者第一版可能使用了不同的函数名称。除了名称之外,这似乎与第 1 章的第一版勘误表相匹配:“pp 11-12:count_if() 的代码是错误的(没有按照它声称的那样做)......”页码似乎匹配。

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


【解决方案1】:

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

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

即,nullptr 与 '\0' 不同。而字符是空字符,叫NUL,但不应该叫NULL字节或NULL字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2021-03-01
    • 2011-05-14
    相关资源
    最近更新 更多