为什么强制转换为数组引用会更改指针的值
Why casting to array reference changes value of pointer?
>我有这个代码片段:
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
本身,而不是first
或second
所指的虚构int[9]
,其地址存储在third
中。
你想要的演员阵容看起来像
void *v=&first;
auto &fifth=*reinterpret_cast<int(*)[3][3]>(v);
相关文章:
- 如何使用基类指针引用派生类成员
- 将常量指针引用绑定到非常量指针
- 如果非动态变量被指针引用,何时超出范围?
- 转换指针引用的字符串
- 指针引用的生存期(以 C++为单位)
- 从 unique_ptr::get 发送指针作为指针引用进入函数
- 指针/引用的 CLion 格式
- 使用模板专用化来比较指针引用
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- C++初始化指针/引用/复制细微差别
- 用数组或指针引用函数?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 强制转换为指针引用是否会导致未定义的行为
- 访问由 void 指针引用的结构的成员
- C 为什么当先前的步骤引发异常时,std :: shared_ptr的指针引用会被破坏
- 动态指针引用数组由三元运算符返回值,但有异常
- 悬空指向 int 和 char* 常量的指针/引用
- C++ 二维数组和指针引用
- 通过使用指针/引用,在C++中使用向量加快计算速度
- C++非类型模板模板到函数指针/引用