我不明白为什么cout
不工作在这个代码:
#include<iostream>
using namespace std;
int main() {
int v = 65;
int* q = &v;
char** o = (char**)&q;
cout << o << endl; // output: 012FFCAC
cout << *o << endl; // output: A
cout << **o << endl; // output: A
printf("%c",*o); // cause an error
printf("%p",*o); // works and the output=&v
cout
在此代码中不起作用
#include<iostream>
using namespace std;
int main() {
char v = 65;
cout << &v << endl; // output: A╠╠╠╠▀?╞«4°O
因为int(通常)是4个字节,65
将非常整齐地放在第一个字节中,而为int分配的其余内存将是0
,这种字节模式恰好与字符串在内存中的存储方式非常接近。
所以当通过char*
访问内存时,大多数情况下它会打印A
,即使大多数打印都是错误的
int v = 65; // Byte pattern on most machines [65,0,0,0]
int* q = &v;
char** o = (char**)&q; // *o now points to [65,0,0,0] ==> ['A',' ',' ',' '] ==> "A"
std::cout << o << std::endl;
// input: char**
// printed as: pointer
// result: 012FFCAC
std::cout << *o << std::endl; // Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A"
std::cout << **o << std::endl; // Undefined Behaviour
// input: char
// printed as: single character
// result: 'A'
printf("%c",*o); // %c expects a [char] type but is given [pointer to char] ERROR
printf("%p",*o); // %p expects a [pointer] type and is given a [pointer to char] OK
由于char
(通常)是1字节,因此没有空终止,一旦开始打印就会停止打印,并且它会继续打印内存中的任何内容,直到遇到0
或访问冲突
char v = 65;
std::cout << &v << std::endl; // &v is not a well-formed null terminated string: Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A<whatever other data is around v in memory>"