在 c++ std::cout<<nullptr 程序崩溃但在 c printf("%s",NULL) 中不是

问题描述

C++

1.

#include<iostream>
#include<cstring>

int main()
{
    char s1[20]="bonapart",s2[]="boy",*k;

    std::cout<<"hey";

    k=strstr(s1,s2);
    std::cout<<k;
    
    std::cout<<"bye";
}

输出

hey

为什么程序会在这里崩溃

2.

#include<iostream>

int main()
{

    std::cout<<"hey";
    
    std::cout<<nullptr;
    
    std::cout<<"hey";
}

输出

[Error] ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::nullptr_t')

为什么会出现这个错误

C

1.

#include<stdio.h>
#include<string.h>

int main()
{
    char s1[20]="bonapart",*k;
    
    printf("hey");
    k=strstr(s1,s2);
    printf("%s",k);
    
    printf("bye");
}

输出

hey(null)bye

在这里工作正常

2.

#include<stdio.h>

int main()
{
    printf("hey");
    
    printf("%s",NULL);
    
    printf("bye");
}

输出

hey(null)bye

工作正常。

那么为什么 C++ 代码在运行时由于空字符串而崩溃,尽管 C 只需为空字符串设置 null 就可以正常工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)