C++ 如何摆脱 - “警告:从 NULL 转换为非指针类型‘char’”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6040382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:23:07  来源:igfitidea点击:

how to get rid of - "warning: converting to non-pointer type 'char' from NULL"?

c++warningsopensuse

提问by Owen

I have this block of code:

我有这个代码块:

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

The line - buffer[bytes] = NULL is giving me a warning: converting to non-pointer type 'char' from NULL. How do I get rid of this warning?

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

回答by Xeo

Don't use NULL? It's generally reserved for pointers, and you don't have a pointer, only a simple char. Just use \0(null-terminator) or a simple 0.

不使用NULL?它通常为指针保留,并且您没有指针,只有一个简单的char. 只需使用\0(null-terminator) 或简单的0.

回答by iammilind

buffer[bytesRead] = 0;// NULL is meant for pointers

buffer[bytesRead] = 0;// NULL 用于指针

As a suggestion, if you want to avoid copying and all then, below can be considered.

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

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

回答by ninjalj

NULLNUL.

NULLNUL

NULLis a constant representing a null pointer in C and C++.

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

NULis the ASCII NUL character, which in C and C++ terminates strings and is represented as \0.

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

You can also use 0, which is exactly the same as \0, since in C character literals have inttype.In C++, character constants are type char.

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