C ++转换静态二维双数组double ** [英] C++ casting static two-dimensional double array to double**
问题描述
我的程式中有这样的矩阵:
I have such matrix in my program:
double m[3][4] =
{
{2, 4, 5, 7},
{4, 5, 1, 12},
{9, 12, 13, -4}
};
我想把它转换为 double **
type。
And I'd like to cast it to double**
type.
我已经尝试过简单的 double ** a =(double **)m;
,但它不工作(当我尝试读取任何值,我获得访问冲突读取位置0x00000000。,这意味着我试图从 NULL $ c $
I've already tried simple double** a = (double**)m;
, but it doesn't work (when I try to read any value, I get "Access violation reading location 0x00000000.", which means I'm trying to read from NULL
adress.
我发现几乎可以使用的解决方案:
I found almost working solution:
double *b = &m[0][0];
double **c = &b;
当我读取字段 c [0] [any]
时,它工作但是同样的NULL地址读取问题发生,当我尝试读取值字段 c [1] [0]
。
> double m [3] [4] 数组以键入 double **
?
What is the proper way to cast my double m[3][4]
array to type double**
?
编辑:
你说这是不可能的,所以我会改变一个问题一点。我如何将二维双数组作为参数传递给函数?我的函数有原型:
edit: You say that's impossible. So I'll change a problem a little bit. How can I pass two-dimensional double array as a parameter to a function? My function has prototype:
void calculate(double **matrix, int n); //where matrix size is always n by n+1
并且它与动态分配的数组。我怀疑只有使它工作的方法是分配新的动态数组和复制原始静态数组一个元素另一个...
And it's working fine with dynamically-allocated arrays. I doubt that only way to make it work is allocating new dynamical array and copy original static array one element by another...
推荐答案
你不能只是转换数组。您将要创建如下所示的内容:
You can't just cast the array. You are going to have to create something like this:
double m[3][4] =
{
{2, 4, 5, 7},
{4, 5, 1, 12},
{9, 12, 13, -4}
};
double *marray[3] = {m[0],m[1],m[2]};
calculate(marray,3);
或者您可以使用循环:
const size_t n = 3;
double *marray[n];
for (size_t i=0; i!=n; ++i) {
marray[i] = m[i];
}
calculate(marray,n);
这篇关于C ++转换静态二维双数组double **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!