【问题标题】:how to get rid of - "warning: converting to non-pointer type 'char' from NULL"?如何摆脱-“警告:从NULL转换为非指针类型'char'”?
【发布时间】:2011-05-18 05:46:55
【问题描述】:

我有这段代码:

int myFunc( std::string &value )
{
    char buffer[fileSize];
    ....
    buffer[bytesRead] = NULL;
    value = buffer;
    return 0;
}

- buffer[bytes] = NULL 这一行给了我一个警告:从 NULL 转换为非指针类型 'char'。我如何摆脱这个警告?

【问题讨论】:

    标签: c++ warnings opensuse


    【解决方案1】:

    不要使用NULL?它一般是为指针保留的,你没有指针,只有一个简单的char。只需使用\0(空终止符)或简单的0

    【讨论】:

      【解决方案2】:

      buffer[bytesRead] = 0; // NULL 表示指针

      作为建议,如果您想避免复制,那么可以考虑以下内容。

      int myFunc (std::string &value)
      {
        s.resize(fileSize);
        char *buffer = const_cast<char*>(s.c_str());
        //...
        value[bytesRead] = 0;
        return 0;
      }
      

      【讨论】:

        【解决方案3】:

        NULLNUL

        NULL 是一个常量,表示 C 和 C++ 中的空指针。

        NUL 是 ASCII NUL 字符,在 C 和 C++ 中终止字符串并表示为 \0

        您也可以使用0,它与\0 完全相同,因为在C 字符文字中具有int 类型。在C++ 中,字符常量是char 类型。

        【讨论】:

        • 这个问题被错误地标记为c,因为代码显然使用了std::string,它是C++。因此,字符串文字不是int,而是正确的char
        • 从您的回答中,我至少可以看到 OP 是如何通过 NULL 初始化字符的。谢谢。 xD
        猜你喜欢
        • 2012-12-05
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-17
        相关资源
        最近更新 更多