I am working on multidimensional arrays. The matrix's data and dimensions are given during runtime, and I tried to access the data with type alias pointer such as below.
It worked well with my code, but I am not sure if it's within c++ standard.
Can I use type alias like this: unknown-dimensional array pointer?
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]
with runtime values uses VLA (Variable Length Array) extension, and so, is not standard C++.
And even with that extension, your cast breaks strict aliasing rules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.