Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将字符*转换为int*C++;_C++_Pointers - Fatal编程技术网

C++ 将字符*转换为int*C++;

C++ 将字符*转换为int*C++;,c++,pointers,C++,Pointers,我有一段代码,我在某处看到它,我试图弄清楚它是如何工作的,但我做不到 就是这样: #include <iostream> using namespace std; int main() { int a = 2; char * p = (char *) &a; *(p + 1) = 1; cout << (int *) p << endl; return 0; } #包括 使用名称空间std; int main(){ I

我有一段代码,我在某处看到它,我试图弄清楚它是如何工作的,但我做不到

就是这样:

#include <iostream>
using namespace std;

int main() {
   int a = 2;
   char * p = (char *) &a;
   *(p + 1) = 1;
   cout << (int *) p << endl;
   return 0;
}
#包括
使用名称空间std;
int main(){
INTA=2;
char*p=(char*)&a;
*(p+1)=1;
库特
如果我想显示p的值,它只显示2,而不是258
预料之中

p
的值是它指向的对象的地址。您的困惑似乎就在这里。如果您取消引用
p
您将得到它指向的对象的值,这是不同的

因此,在您的情况下,
p
被初始化为
a
的地址。之后,不会向其分配任何内容(例如,您不执行
p=&SomeOtherObject


如果
sizeof(int)
sizeof(char)
相同,则可能是未定义的行为
*(p+1)=1;
是未定义的行为。为什么p的值在转换为int时不会改变?它不应该是258而不是2吗?强制比特8-15到00000001是一种依赖于系统的黑客行为。代码所有者为什么要这样做?它不像
a=(a&~0xFF00)| 0x0100
很慢?@unwind它是
sizeof(char)@Giorgi是的,我错误地认为
sizeof(int)>sizeof(char)
是真的,但这应该是
=
,这使得代码访问
int
的第二个
char
   cout << (int *) p << endl; // Print value of pointer -which is address
*(p+1) = 1
int a = 2;
cout << sizeof(a) << endl;       // 4 (int is 4 bytes)
cout << sizeof(&a) << endl;      // 8 (64b machine, so pointer is 8 bytes)

char *p = (char *) &a;           // p points to first byte of a (normally 4 bytes)
cout << (int) *p << endl;        // 2    // Little Endian, the first byte is actually the last
cout << (int) *(p + 1) << endl;  // 0

*(p + 1) = 1;                    // second byte of a is now set to 1
cout << a << endl;               // a now changes to 258 (0000 0001 0000 0010)