[英]C++ char single quotes vs double quotes & memory inner workings
I want to know what the program does memory-wise during runtime as it comes across the following: 我想知道程序在运行时在内存方面的作用,因为它遇到以下情况:
char chr = 'a';
char chrS[] = "a";
cout << "Address: " << &chr << endl;
cout << "Address: " << &chrS << endl;
This produces the following: 这产生以下结果:
Address: a�c�3�
Address: 0x7fff33936280
Why can't I get the memory address of "chr"? 为什么我不能得到“chr”的内存地址?
Because &chr
yields a char*
(implicit addition of const
here) and cout
assumes that it is a string and therefore null terminated, which it is not. 因为
&chr
产生一个char*
(这里隐式添加const
), cout
假定它是一个字符串,因此null终止,但它不是。
However, &chrS
yields a char(*)[]
, which will not decay to a const char*
and therefore will be output through the operator<<(std::ostream&, const void*)
overload, which prints the address. 但是,
&chrS
产生一个char(*)[]
,它不会衰减为const char*
,因此将通过operator<<(std::ostream&, const void*)
重载输出,它会打印地址。
If you want this behaviour for a const char*
you will have to perform an explicit cast. 如果您想要
const char*
这种行为,则必须执行显式转换。 The fact that there is no difference between a C-string and a pointer to a single character is one of the primary flaws of C-strings. C字符串和指向单个字符的指针之间没有区别这一事实是C字符串的主要缺陷之一。
Try 尝试
cout << "Address: " << hex << (long)(&chr) << endl;
Otherwise, when it gets the pointer to a char, it thinks you're giving it a string and tries to print it as one. 否则,当它获得指向char的指针时,它会认为你给它一个字符串并尝试将其打印为一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.