我正在尝试这个指针技巧,但我不知道如何修复它,我在 ubuntu 12.04 64 位上运行 g++ 4.6。查看下面的代码:
int arr[5];
arr[3] = 50;
((short*) arr)[6] = 2;
cout << arr[3] << endl;
逻辑是:因为short
是 2 个字节,int
是4个字节,我想更改arr[3]
中的前2个字节,同时将第二个 2 个字节的值保持为 50。所以我只是搞乱了位模式。不幸的是,sizeof(int*)
和 sizeof(short*)
都是8字节。是否存在返回大小为 2 字节的指针的类型转换?
更新:
我意识到这个问题写得不好,所以我会解决这个问题:
cout << arr[3] << endl;
的输出我得到的是2。我想得到的输出既不是2也不是50,而是一个很大的数字,表明int位模式的左边部分已经改变,而右边部分(第二个2位) 存储在 arr[3] 中的 int 仍然没有改变。
最佳答案
sizeof(int*)
和 sizeof(short*)
都将是相同的——sizeof(void*)
也是一样的> -- 您要求的是指针的大小,而不是指针指向的对象的大小。
改用sizeof(int)
或sizeof(short)
。
现在,对于您的代码片段,您正在假设 endianness你正在运行的机器。给定平台上 int
的“第一”部分可能是地址较高的字节,也可能是地址较低的字节。
例如,你的内存块可能是这样布局的。假设最低有效字节的索引为零,最高有效字节的索引为一。在大端架构上,int 可能如下所示:
<------------- 4 bytes --------------->
+---------+---------+---------+---------+
| int:3 | int:2 | int:1 | int:0 |
| short:1 | short:0 | short:1 | short:0 |
+---------+---------+---------+---------+
请注意 int 中的第一个 short —— 在你的例子中应该是 ((short*) arr)[6]
—— 如何包含 int 的最高有效位,而不是最不重要。因此,如果您覆盖 ((short*) arr)[6]
,您将覆盖 arr[3]
的最高有效位,这似乎是您想要的。但是 x64 不是大端机器。
在小端架构上,你会看到这个:
<------------- 4 bytes --------------->
+---------+---------+---------+---------+
| int:0 | int:1 | int:2 | int:3 |
| short:0 | short:1 | short:0 | short:1 |
+---------+---------+---------+---------+
导致相反的行为——((short*) arr)[6]
将是 arr[3]
的最低有效位,而 ((short*) arr)[7]
将是最重要的。
这是我的机器碰巧做的——你的机器可能不同:
C:\Users\Billy\Desktop>type example.cpp
#include <iostream>
int main()
{
std::cout << "Size of int is " << sizeof(int) << " and size of short is "
<< sizeof(short) << std::endl;
int arr[5];
arr[3] = 50;
((short*) arr)[6] = 2;
std::cout << arr[3] << std::endl;
((short*) arr)[7] = 2;
std::cout << arr[3] << std::endl;
}
C:\Users\Billy\Desktop>cl /W4 /EHsc /nologo example.cpp && example.exe
example.cpp
Size of int is 4 and size of short is 2
2
131074
关于c++ - C/C++ 指针技巧修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105432/