C++重新解释_cast
在运行该程序时:
#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}
我得到以下输出:
4202656
这个数字代表什么?是内存地址吗?但是,内存地址是什么? “abc”不是作为字符数组存储在内存中吗?
谢谢。
In running this program:
#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}
I got the following output:
4202656
What does this number represent? Is it a memory address? But, memory address of what? Isn't "abc" stored as an array of characters in memory?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是未定义的。 sizeof(int) 可能不等于 sizeof(char*)。我不确定严格的别名规则是否也适用于此。
但实际上,假设它们的大小确实相等(大多数 32 位平台),则 4202656 将表示数组中第一个字符的地址。我会这样更干净地做到这一点:
It is undefined. sizeof(int) might not be equal to sizeof(char*). I'm not sure if strict aliasing rules apply here as well.
In practice however, assuming their sizes are indeed equal (most 32-bit platforms), 4202656 would represent the address of the first character in the array. I would do this more cleanly this way:
它可能是字符“a”的地址。
虽然我不认为这是有保证的(即 int 可能不够长来保存地址)。
It is probably the address of the character 'a'.
Though I don;t think this is guaranteed (i.e. an int may not be long enough to hold the address).
您可能想看看这个问题: casting via void* 而不是使用reinterpret_cast
简短的回答是,它可以是任何东西。
You probably want to look at the question: casting via void* instead of using reinterpret_cast
The short answer is that it could be anything at all.
这是“abc”第一个字符的内存地址,即“a”。因为数组是一个指针,指向数组的第一个值。
如果你这样做
cout << *(name++)
通常会打印“b”。因此,当转换
name
时,您尝试转换指向“a”的地址This the memory address of the first character of "abc", so "a". Because an array is a pointer who point to the first value of the array.
If you do
cout << *(name++)
normaly "b" is printed.So when cast
name
, you try to cast the adress who point to "a"