Noa*_*ahR 20 c c++ casting matrix multidimensional-array
我有一个函数,它采用指向浮点数组的指针.基于其他条件,我知道指针实际上指向2x2 OR 3x3矩阵.(实际上内存最初是这样分配的,例如float M [2] [2])重要的是我想在函数体中做出这个决定,而不是作为函数参数.
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...
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用模板和其他技术来更好地解决这个问题.我的问题是关于如何在###评论中进行这样的演员表.使用C++.
eca*_*mur 26
float (*somethingAsMatrix)[2] = (float (*)[2]) matrixReturnAsArray;
Run Code Online (Sandbox Code Playgroud)
float *可以指向浮点数数组的第一个元素,并且应该可以将该数组类型重新解释为可广播的。并且该转换的结果可能指向a的第一个元素,float [][]因此应重新解释为可转换为该类型,依此类推。您应该能够撰写这样的演员表并直接做
float (&arr)[2][2] = *reinterpret_cast<float (*)[2][2]>(matrixReturnAsArray);
Run Code Online (Sandbox Code Playgroud)
类型的参数float **不相同,因此不应以这种方式使用。
为避免出现未定义的行为,指针必须源自实际的多维数组,并且如果float*直接使用,则不能访问多维矩阵的第一行。
void foo(float *f) {
f[3] = 10.;
float (&arr)[2][2] = *reinterpret_cast<float (*)[2][2]>(f);
arr[1][1] = 10.;
}
void main() {
float a[2][2];
foo(&a[0][0]); // f[3] = 10.; is undefined behavior, arr[1][1] = 10. is well defined
float b[4];
foo(&b[0]); // f[3] = 10.; is well-defined behavior, arr[1][1] = 10. is undefined
}
Run Code Online (Sandbox Code Playgroud)
由于float arr[2][2];没有保证&arr[0][1] + 1是一样的&arr[1][0],据我已经能够确定。因此,尽管您可以这样做f[i*width + j]将一维数组用作多维数组,但是您不能像对待一维数组那样对待多维数组。
最好使用C ++的编译时类型安全性,而不是仅仅依赖于不意外传递错误的内容或执行错误的reinterpret_cast。为了使用原始数组获得类型安全,您应该使用对所需原始数组类型的引用:
void foo(float (&f)[2][2]) {}
void foo(float (&f)[3][3]) {}
Run Code Online (Sandbox Code Playgroud)
如果要按值传递数组,则不能使用原始数组,而应使用诸如std :: array之类的东西:
void foo(std::array<std::array<float,2>,2> f) {}
void foo(std::array<std::array<float,3>,3> f) {}
Run Code Online (Sandbox Code Playgroud)