如何将原始指针静态化为指向固定数组的指针

How to static_cast raw pointer to pointer-to-fixed-array

本文关键字:指针 数组 原始 静态      更新时间:2023-10-16

我在使用一个将指针指向固定数组的函数时遇到问题。我有一个简单的指针,编译器不允许我将它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个维度之外的每个维度中指定大小。编译器需要知道该信息来计算指针算术运算。