c++ - 为什么编译器将字符打印为笑脸
问题描述
#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= ☺
解决方案
打印(如)的重载operator<<
不会像重载一样打印指针指向的地址。相反,它实际上读取了指向地址的内容 - 并继续读取,直到遇到 a ,这就是起作用的原因。char*
char *p0;
void*
\0
std::cout << "Hello world";
"Hello world"
(以 null 结尾的 C 字符串)本身衰减为 a const char*
,指向H
,并且operator<<
重载从那里开始读取并输出每个字符,直到它看到 a\0
然后它停止。
笑脸只是一个快乐的巧合。存储在指定地址的值恰好形成一个 unicode 序列 - 形成一个笑脸。
推荐阅读
- python - 如何修复意外分配的内置函数名称?
- javascript - 如何从 Java 调用 HTML/PHP 中的 Web 服务使用 Javascript/AJAX
- javascript - 在对象数组中查找 angular 6/typescript/javascript
- javascript - flv.js 无法使用 avc1 编解码器
- html - 将值从一个表传递到另一个 html 页面
- c++ - 如何使用中值滤波算法去除胡椒噪声
- c++ - 在 if 语句中声明时如何访问类对象?(在 C++ 中)
- java - java - 如何在java swing中加载本地html文件?
- centos7 - Clearcase - 无法访问 VOB - ls:读取目录 - 权限被拒绝
- android - 如何在 viewpager 中使用 webview 的水平滚动?