为什么强制转换为数组引用会更改指针的值?

时间:2019-04-08 11:42:59

标签: c++

我有以下代码段:

int main()
{
    int first[3][3] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
    int (&second)[9] = reinterpret_cast<int(&)[9]>(first);

    for(auto &i: second)
        std::cout << i << " ";

    void * third = (void *) second;

    int (*fourth)[3]   = reinterpret_cast<int(*)[3]>(third);
    int (&fifth)[3][3] = reinterpret_cast<int(&)[3][3]>(third);

    std::cout << first  << " "
              << second << " "
              << third  << " "
              << fourth << " "
              << fifth  << std::endl;

    for (int i = 0; i < 3; ++i) {
        for (auto &x: fourth[i]) {
            std::cout << x << " ";
        }

        std::cout << std::endl;
    }

    for (auto &row: fifth) {
        for (auto &x: row) {
            std::cout << x << " ";
        }
        std::cout << std::endl;
    }
}

基本上我想将int [3] [3]转换为void *,然后返回int [3] [3]。

将void *铸造为int(*)[3]可以正常工作-显示所有元素。但是,强制转换为int(&)[3] [3]无效,并且第五个值不同,打印的第一到第四个值相同。

是否存在将void *转换为多维数组的正确方法?

1 个答案:

答案 0 :(得分:2)

Given float f;, reinterpret_cast<int&>(f) produces an lvalue of type int that refers to f. Similarly,

float f,*fp=&f;
do_something(reinterpret_cast<int&>(fp));

passes an lvalue referring to fp, not f. So in your case, fifth refers to third itself, not first or the fictitious int[9] to which second refers and whose address is stored in third.

The cast you want looks like

void *v=&first;
auto &fifth=*reinterpret_cast<int(*)[3][3]>(v);