繁体   English   中英

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

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

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

它适用于我的代码,但我不确定它是否符合 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++。

即使有了这个扩展,你的演员也打破了严格的别名规则。

暂无
暂无

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

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