简而言之,我通过if
语句检查两个char *是否为nullptr或为空,但是我收到一条警告,说我正在取消引用空指针。
// mplate is a reference to a class
if ((mplate.m_plate != nullptr || mplate.m_plate[0] != '\0') || (plate != nullptr || plate[0] != '\0')) {
// Do something
}
else {
// do something else
}
所以基本上我想在
if
语句中说的是mplate.mplate
或plate
是空的还是nullptr
这样做,否则做其他事情。Severity Code Description Project File Line Suppression State
Warning C6011 Dereferencing NULL pointer 'make'.
Warning C6011 Dereferencing NULL pointer 'model'.
Warning C6011 Dereferencing NULL pointer 'mplate.m_plate'.
Warning C6011 Dereferencing NULL pointer 'plate'.
Warning C6011 Dereferencing NULL pointer 'plate'.
最佳答案
你正在做类似的事情
if (p != nullptr || *p)
也就是说,仅当指针为
nullptr
时,您才取消引用。这意味着如果指针有效,则不执行任何操作;如果指针无效(即UB),则取消引用。您需要像这样执行逻辑
and
if (p != nullptr && *p)
即仅在指针不是
nullptr
时才取消引用。
关于c++ - 检查char *是否为null或为空时取消引用NULL指针警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61189312/