将char*转换为int*C++

convert char* to int* C++

本文关键字:int C++ 转换 char      更新时间:2023-10-16

我在某个地方看到了这段代码,我试图弄清楚它是如何工作的,但我做不到。

这就是:

#include <iostream>
using namespace std;
int main() {
   int a = 2;
   char * p = (char *) &a;
   *(p + 1) = 1;
   cout << (int *) p << endl;
   return 0;
}

我认为在p中,它存储变量a的二进制值,就像00000010一样。然后在下一个直接地址中存储CCD_ 2。当我尝试打印(int *)p时,它从该地址中提取4个字节,并将其转换为int。

当我运行这个程序时,结果并不是预期的那样。它只显示变量a的地址。未观察到任何变化。

你能解释一下这是怎么回事吗?为什么?

PS:如果我想显示p的值,它只显示2,而不是我预期的258。

cout << (int *) p << endl;将与cout << &a << endl;相同(只是a的地址)。

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)

PS:如果我想显示p的值,它只显示2,而不是258预期。

p是它所指向的对象的地址。你的困惑似乎在这里。若你们取消引用p,你们会得到它所指向的对象的值,这是不同的。

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

   cout << (int *) p << endl; // Print value of pointer -which is address

所以上面您正在打印p的值,即a的地址。

如前所述,请记住

*(p+1) = 1

如果sizeof (int)sizeof (char) 相同,则可能是未定义的行为