简体   繁体   English

c++ 动态维数组的别名指针

[英]c++ aliasing pointer of dynamic dimensional array

I am working on multidimensional arrays.我正在研究多维 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.它适用于我的代码,但我不确定它是否符合 c++ 标准。

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++.具有运行时值int (*)[a][b][c]使用 VLA(可变长度数组)扩展,因此不是标准的 C++。

And even with that extension, your cast breaks strict aliasing rules.即使有了这个扩展,你的演员也打破了严格的别名规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM