将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
一样。然后在下一个直接地址中存储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)
相同,则可能是未定义的行为
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- C++程序在循环后给出奇怪的int值
- 如何计算数据类型的范围,例如int
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)