动态维度数组的 C++ 别名指针

c++ aliasing pointer of dynamic dimensional array

本文关键字:C++ 别名 指针 数组 动态      更新时间:2023-10-16

我正在研究多维数组。 矩阵的数据和维度在运行时给出, 我尝试使用类型别名指针访问数据,如下所示。

它与我的代码配合得很好,但我不确定它是否在 c++ 标准范围内。

我可以像这样使用类型别名吗:未知维数组指针?

cin >> a; //1
cin >> b; //2
cin >> c; //3
int* buf = new int[100]; //just to allocate some memory for test
using arr_t = int (*)[a][b][c]; //type alias of pointer of array
arr_t arr = reinterpret_cast<arr_t>(buf);
buf[3] = 1;
cout << arr[0][1][0] << endl; // 1 (It's easier than buf[b*c*0 + c*1 + 0])
cout << (void*)&buf[3] << endl; //0x18b8e78
cout << (void*)&(*arr)[0][1][0] << endl; //0x18b8e78

具有运行时值的int (*)[a][b][c]使用VLA(可变长度数组(扩展名,因此不是标准C++。

即使有了该扩展名,您的演员表也会违反严格的别名规则。