我得到了这些结果。我究竟做错了什么?
const char *c = "\0";
cout << (c == NULL); // false
cout << (c == nullptr); //false
Run Code Online (Sandbox Code Playgroud) 默认情况下,我们如何知道指针未初始化为NULL?有一个类似的问题针对为什么默认情况下没有用NULL初始化指针? 只是为了检查,这是一个非常简单的代码,只是为了查看默认情况下指针是否设置为NULL.
#include <iostream>
using namespace std;
int main()
{
int* x;
if(!x)
cout << "nullptr" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在输出中,我收到了nullptr消息.如果有人能澄清这一点我感激不尽.
long cread(long *xp) {
return (xp? *xp : 0);
}
Run Code Online (Sandbox Code Playgroud)
它无效,因为它可能尝试从空地址读取
所以解决方案建议使用此代码
long cread_alt(long *xp){
long tem = 0;
if(*xp > 0){
tem = *xp;
}
return tem;
Run Code Online (Sandbox Code Playgroud)
但我认为它也无效,因为if(*xp > 0)当xp指向空地址时仍然有缺陷.
所以我想到了这段代码
long cread_alt2(long *xp){
long tem = 0;
if(xp != NULL){
tem = *xp;
}
return tem;
}
Run Code Online (Sandbox Code Playgroud)
我有这个吗?
考虑以下代码:
int main() {
int *i = nullptr;
delete i;
}
Run Code Online (Sandbox Code Playgroud)
问题: