gpt4 book ai didi

c++ - 将 char* 转换为 int* C++

转载 作者:太空狗 更新时间:2023-10-29 20:37:49 25 4
gpt4 key购买 nike

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

就是这样:

#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)

关于c++ - 将 char* 转换为 int* C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com