将多维数组转换为 C++ 中的指针

Converting multidimensional arrays to pointers in c++(将多维数组转换为 C++ 中的指针)
本文介绍了将多维数组转换为 C++ 中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个如下所示的程序:

I have a program that looks like the following:

double[4][4] startMatrix;
double[4][4] inverseMatrix;
initialize(startMatrix) //this puts the information I want in startMatrix

我现在想计算startMatrix的逆并将其放入inverseMatrix.为此,我有一个库函数,其原型如下:

I now want to calculate the inverse of startMatrix and put it into inverseMatrix. I have a library function for this purpose whose prototype is the following:

void MatrixInversion(double** A, int order, double** B)

将 A 的倒数放入 B 中.问题是我需要知道如何将 double[4][4] 转换为 double** 以提供给函数.我试过只是用明显的方式"来做:

that takes the inverse of A and puts it in B. The problem is that I need to know how to convert the double[4][4] into a double** to give to the function. I've tried just doing it the "obvious way":

MatrixInversion((double**)startMatrix, 4, (double**)inverseMatrix))

但这似乎不起作用.这真的是正确的做法吗?

but that doesn't seem to work. Is that actually the right way to do it?

推荐答案

不,没有正确的方法可以专门解决这个问题.double[4][4] 数组不能转换为 double ** 指针.这是实现二维数组的两种替代的、不兼容的方法.需要改变一些东西:函数的接口,或者作为参数传递的数组的结构.

No, there's no right way to do specifically that. A double[4][4] array is not convertible to a double ** pointer. These are two alternative, incompatible ways to implement a 2D array. Something needs to be changed: either the function's interface, or the structure of the array passed as an argument.

执行后者的最简单方法,即使您现有的 double[4][4] 数组与函数兼容,是创建 double 类型的临时索引"数组*[4] 指向每个矩阵中每一行的开头

The simplest way to do the latter, i.e. to make your existing double[4][4] array compatible with the function, is to create temporary "index" arrays of type double *[4] pointing to the beginnings of each row in each matrix

double *startRows[4] = { startMatrix[0], startMatrix[1], startMatrix[2] , startMatrix[3] };
double *inverseRows[4] = { /* same thing here */ };

并传递这些索引"数组

MatrixInversion(startRows, 4, inverseRows);

一旦函数完成工作,您可以忘记 startRowsinverseRows 数组,因为结果将放入您原来的 inverseMatrix正确排列.

Once the function finished working, you can forget about the startRows and inverseRows arrays, since the result will be placed into your original inverseMatrix array correctly.

这篇关于将多维数组转换为 C++ 中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)