char 类型的 NULL 指针会导致程序终止吗?

声明char 类型的NULL指针,在输出指针变量的值之后,程序就像是终止了一样,导致后面的判断语句不执行了。请大神指点下。

相关代码:


#include<iostream>
#include<string>
using namespace std;

int main() {
    // int *var = NULL;
    // short *var = NULL;
    // long *var = NULL;
    // float *var = NULL;
    // double *var = NULL;
    // bool *var = NULL;

    char *var = NULL;
    // string *var = NULL;

    cout << "var's value is " << var << endl;

    // 很奇怪的现象是:
    // 当指针类型为 char 时, 下面的判断语句不执行了!
    if(var) {
        cout << "var is not null pointer." << endl;
    } else {
        cout << "var is null pointer." << endl;
    }
}


期望在控制套输出的结果是:

var's value is 0
var is null pointer.

实际在控制台输出的结果是:

var's value is 0



补充说明:
1. 使用 g++ 编译的时候并未提示错误。
2. 将指针类型修改为 int 或者 string 的时候,均可得到期望的结果。
3. 使用 VS 调试这段代码的时候,弹出了 Visual Studio 2019 已经停止了工作 的提示

#include<iostream>
#include<string>
using namespace std;

int main() {

    char* var = NULL;

    cout << "var's value is " << (int)var << endl;
    if (var) {
        cout << "var is not null pointer." << endl;
    }
    else {
        cout << "var is null pointer." << endl;
    }
}




你可以尝试一下这样写

    const char* var = "123";
    cout << "var's value is " << var << endl;
        cout << "var's value is " << "123"<< endl;

cout 把char * 理解成了指向字符串的指针了把

希望这个可以帮到你

#include<iostream>
#include<string>
using namespace std;
int a;
char b;
float c;
double d;
bool boo;
string str;
int *e;
char *f;
float *g;
double *h;
string *s;
int main() {
    cout<<"int "<<a<<endl<<"char "<<b<<endl<<"float "<<c<<endl<<"double "<<d<<endl<<"string "<<str<<endl<<"bool "<<boo<<endl;
    cout<<"int* "<<e<<endl<<"float* "<<g<<endl<<"double* "<<h<<endl<<"string* "<<s<<endl<<"char* "<<f<<endl;
    return 0;
}