[英]cout with pointers c++
I can not understand why cout
does not work in this code:我不明白为什么
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
And cout
does not work else in this code并且
cout
在此代码中不起作用
#include<iostream>
using namespace std;
int main() {
char v = 65;
cout << &v << endl; // output: A╠╠╠╠▀?╞«4°O
Because an int is (usually) 4 bytes 65
will fit quite neatly into just the first byte and the rest of the memory allocated for the int will be 0
this byte pattern happens to match up very closely to how strings are stored in memory.因为一个 int(通常)是 4 个字节,所以
65
将非常适合第一个字节,而分配给 int 的 memory 的 rest 将是0
,这个字节模式恰好与字符串在 memory 中的存储方式非常匹配。
So when the memory is accessed through a char*
it will print A
most of the time even though most of the prints were ill formed因此,当通过
char*
访问 memory 时,它会在大多数时间打印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','\0','\0','\0'] ==> "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
Since a char
is (usually) 1 byte there is no null terminand to stop the printing once it starts and it keeps printing whatever is around in memory until it runs into a 0
or an access violation由于
char
(通常)是 1 个字节,因此一旦开始打印就没有 null 终止符停止打印,并且它会一直打印 memory 中的任何内容,直到遇到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>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.