C/C++指针技巧修复

nax*_*nge 0 c c++ pointers dereference

我正在尝试这个指针技巧,我无法弄清楚如何修复它,我在64位的ubuntu 12.04上运行g ++ 4.6.看看下面的代码:

int arr[5];
arr[3] = 50;
((short*) arr)[6] = 2;
cout << arr[3] << endl;
Run Code Online (Sandbox Code Playgroud)

逻辑是:因为short是2个字节,int是4个字节,我想改变前2个字节arr[3],同时保持后2个字节的值为50.所以我只是搞乱位模式.不幸的是,sizeof(int*)sizeof(short*)都是8个字节.是否存在返回大小为2字节的指针的类型转换?

更新:

我意识到这个问题编写得很糟糕,所以我会解决这个问题:cout << arr[3] << endl;我得到的输出是2.我想得的输出既不是2也不是50,而是大数,表示左边的部分int位模式的更改已经更改,而存储在arr [3]中的int的右侧部分(第二个2位)仍未更改.

Bil*_*eal 5

sizeof(int*)并且sizeof(short*)两者都将是相同的 - sizeof(void*)你将要求指针的大小,而不是指针所指向的东西的大小.

使用sizeof(int)sizeof(short)代替.


现在,至于您的代码片段,您正在假设您正在运行的机器的字节顺序.int给定平台上的"第一"部分可以是具有较高地址的字节,或具有较低地址的字节.

例如,您的内存块可能会像这样布局.假设最低有效字节的索引为零,最高有效字节的索引为1.在大端架构上,int可能如下所示:

 <------------- 4 bytes --------------->
+---------+---------+---------+---------+
| int:3   | int:2   | int:1   | int:0   |
| short:1 | short:0 | short:1 | short:0 |
+---------+---------+---------+---------+
Run Code Online (Sandbox Code Playgroud)

注意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 |
+---------+---------+---------+---------+
Run Code Online (Sandbox Code Playgroud)

导致相反的行为 - ((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
Run Code Online (Sandbox Code Playgroud)


shf*_*301 5

你的问题是由于字节序.Intel CPU是小端,意味着int的第一个字节存储在第一个地址中.让我举个例子:

我们假设arr [3]位于地址10:

然后arr[3] = 50;将以下内容写入内存

10:   0x32
11:   0x00
12:   0x00
13:   0x00
Run Code Online (Sandbox Code Playgroud)

并将((short*) arr)[6] = 2;以下内容写入内存

10:  0x02
11:  0x00
Run Code Online (Sandbox Code Playgroud)