繁体   English   中英

将char *转换为int * C ++

[英]convert char* to int* C++

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

就是这个 :

#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 比在下一个直接地址它存储00000001 当我尝试打印(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)相同,则可能是未定义的行为

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM