【问题标题】:why does compiler print char as smilie [duplicate]为什么编译器将char打印为笑脸[重复]
【发布时间】:2021-10-23 06:40:04
【问题描述】:
#include<iostream>
using namespace std;

int main(){
    int a=1025;

    int *p=&a;
    cout<<"Size of integer is: "<<sizeof(int)<<" bytes"<<endl;
    cout<<"Address= "<<p<<" Value= "<<*p<<endl;

    char *p0;
    p0=(char*)p;
    cout<<"Size of char is: "<<sizeof(char)<<" bytes"<<endl;
    cout<<"Address= "<<p0<<"Value= "<<*p0<<endl;
    cout<<"It printed smilie above";

    return 0;
}

为什么char的地址和值被打印成笑脸?

我得到的输出是:

Size of integer is: 4 bytes  
Address= 0x61ff04 Value= 1025
Size of char is: 1 bytes     
Address= ☺♦Value= ☺

【问题讨论】:

  • 你希望它打印什么?

标签: c++ cout


【解决方案1】:

打印char*(如char *p0;)的overload for operator&lt;&lt; 不会像void* 的重载一样打印指针指向的地址。相反,它实际上读取了指定地址的内容 - 并继续读取,直到遇到 \0,这就是 std::cout &lt;&lt; "Hello world"; 工作的原因。

"Hello world"(一个以空结尾的 C 字符串)本身会衰减为 const char*,指向 H,然后 operator&lt;&lt; 重载从那里开始读取并输出每个字符,直到它看到 \0 和然后它就停止了。

笑脸只是一个快乐的巧合。存储在指定地址的值恰好形成了一个 unicode 序列 - 形成了一个笑脸。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2020-07-15
    • 1970-01-01
    • 2021-11-09
    • 2017-05-25
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多