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

Why casting to array reference changes value of pointer?

本文关键字:指针 引用 转换 数组 为什么      更新时间:2023-10-16

>我有这个代码片段:

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]不起作用,第五个的值不同,第一个到第四个打印给出相同的值。

有没有正确的方法将空隙*转换为多维阵列?

给定float f;reinterpret_cast<int&>(f)产生一个类型为int的左值,指的是f。 同样地

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

传递一个引用fp的左值,而不是f。 因此,在您的情况下,fifth指的是third本身,而不是firstsecond所指的虚构int[9],其地址存储在third中。

你想要的演员阵容看起来像

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