在运行此程序:C++的reinterpret_cast
#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}
我得到了以下的输出:
4202656
是什么号码代表什么?它是一个内存地址吗?但是,内存地址是什么?不是“abc”作为内存中的字符数组存储吗?
谢谢。
在运行此程序:C++的reinterpret_cast
#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}
我得到了以下的输出:
4202656
是什么号码代表什么?它是一个内存地址吗?但是,内存地址是什么?不是“abc”作为内存中的字符数组存储吗?
谢谢。
这是未定义的。 sizeof(int)可能不等于sizeof(char *)。我不确定这里是否也适用严格的别名规则。
但实际上,假设它们的大小确实相等(大多数32位平台),则4202656将表示阵列中第一个字符的地址。我会这样做更干净:
#include <iostream>
int main()
{
const char *name = "abc"; // Notice the const. Constant string literals cannot be modified.
std::cout << static_cast<const void*>(name) << std::endl;
}
它可能是字符'a'的地址。
虽然我不认为这是有保证的(即一个int可能不足以保存地址)。
约克。当我输入char * name =“abc”时,我得到相同的输出 – Simplicity 2011-01-28 11:24:47
你可能想看看这个问题:casting via void* instead of using reinterpret_cast
简短的回答是,它可能是任何东西。
这是“abc”的第一个字符的内存地址,所以是“a”。因为数组是指向数组的第一个值的指针。
如果你这样做cout << *(name++)
正常打印“b”。
投下name
时,尝试投谁指向“一”
reinterpret_cast运算符产生一个新类型,有相同的位模式作为参数的值ADRESS。你正在使用哪种编译器? g ++给出了一个错误。 – DumbCoder 2011-01-28 11:21:51
@DumbCoder。当我键入`char * name =“abc”;`时,我得到**相同**输出 – Simplicity 2011-01-28 11:23:55