如何将原始指针静态化为指向固定数组的指针
How to static_cast raw pointer to pointer-to-fixed-array
我在使用一个将指针指向固定数组的函数时遇到问题。我有一个简单的指针,编译器不允许我将它static_cast
到指向数组类型的指针。
下面是一些示例代码:
int main()
{
typedef int (*Arr3)[3];
int a[3] = {1,2,3};
int* p = &a[0];
Arr3 b = static_cast<Arr3>(p);
}
错误消息:
prog.cpp:11:10: error: static_cast from 'int *' to 'Arr3' (aka 'int (*)[3]') is not allowed
Arr3 b = static_cast<Arr3>(p);
^~~~~~~~~~~~~~~~~~~~
1 error generated.
我很确定我可以使用reinterpret_cast
,但这真的是我唯一的选择吗?还是我错过了什么?
这里不能完全是static_cast
,但有一个技巧比reinterpret_cast
更安全:
#include <iostream>
using std::cout;
typedef int (*arr3p)[3];
typedef int arr3[3];
inline arr3& to_arr3(arr3 p)
{
return *(arr3p)(p);
}
inline arr3p to_arr3p(arr3 p)
{
return (arr3p)(p);
}
int main() {
arr3 a = {1, 2, 3};
int *p = &a[0];
arr3p foo = &to_arr3(p);
cout << (*foo)[0] << ", ";
arr3p bar = to_arr3p(p);
cout << (*bar)[1] << ", ";
arr3& baz = to_arr3(p);
cout << baz[2] << std::endl;
return 0;
}
我认为你的演员阵容不正确
Arr3 b = static_cast<Arr3>(p);
应该是
Arr3 b = static_cast<Arr3>(&a);
事实上,演员阵容是没有必要的。简单
Arr3 b = &a;
可以。
一维数组与指针兼容,但多维数组则不然。例如,
int *p = (int*)1;
int (*s)[3] = (int (*)[3])2;
printf("%d,%dn", sizeof(int*), sizeof(int (*)[3]));
printf("%d,%dn", ++p,++s);
输出为:
8,8
5,14
它们都是指针类型,所以它们的大小是64位机器中的8字节。++s
,此数组指针将前进3个元素,但++p
,p将仅前进1个元素。当我们声明指针数组时,我们必须在除第1个维度之外的每个维度中指定大小。编译器需要知道该信息来计算指针算术运算。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空