首页 > 解决方案 > 为什么编译器将字符打印为笑脸

问题描述

#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

解决方案


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

"Hello world"(以 null 结尾的 C 字符串)本身衰减为 a const char*,指向H,并且operator<<重载从那里开始读取并输出每个字符,直到它看到 a\0然后它停止。

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


推荐阅读