如何将简单指针转换为固定大小的多维数组?

2021-12-18 00:00:00 matrix multidimensional-array c casting c++

我有一个函数,它接受一个指向浮点数组的指针.根据其他条件,我知道指针实际上指向一个 2x2 OR 3x3 矩阵.(实际上内存最初是这样分配的,例如 float M[2][2] )重要的是我想在函数体中做出这个决定,而不是作为函数参数.

I have a function that takes a pointer to a floating point array. Based on other conditions, I know that pointer is actually pointing to a 2x2 OR 3x3 matrix. (in fact the memory was initially allocated as such, e.g. float M[2][2] ) The important thing is I want to make this determination in the function body, not as the function argument.

void calcMatrix( int face, float * matrixReturnAsArray )
{
    // Here, I would much rather work in natural matrix notation
    if( is2x2 )
    {
        // ### cast matrixReturnAsArray to somethingAsMatrix[2][2]
        somethingAsMatrix[0][1] = 2.002;
        // etc..
    }
    else if(is3x3)
    { //etc...
    }

}

我知道我可以使用模板和其他技术来更好地解决这个问题.我的问题实际上是关于如何在 ### 评论中进行这样的演员表.使用 C++.

I am aware that I could use templates and other techniques to better address this problem. My question is really about how to make such a cast at the ### comment. Working in C++.

推荐答案

float (*somethingAsMatrix)[2] = (float (*)[2]) matrixReturnAsArray;

相关文章