使用 C++ 的二维数组
我有一个函数,它接受一个指向指针 an 作为参数的指针.
I have a function that takes a pointer to a pointer an as argument.
func(double **arr, int i);
在 main 函数中,数组定义如下:
where in the main function the array is defined as follows:
double arr[][] = //some initialization here;
我怎样才能从我的主代码中调用这个函数.我尝试了以下但它给出了错误
How can I call this function from my main code. I tried the following but it gives an error
func (&arr);
不起作用.任何帮助将非常感激.谢谢
Doesn't work. Any help would be much appreciated. Thanks
推荐答案
A double **p
与 double[][] a
不是一回事,所以你不能通过一个作为另一个.
A double **p
is not the same thing as a double[][] a
, so you can't pass one as the other.
特别是二维数组变量是一个(单个!)包含双精度的内存块,您可以使用 [][]
语法访问它.这要求编译器知道数组的维数,以便它可以计算每个元素的正确偏移量.它也可以透明地衰减到指向该内存块的指针,但是这样做会失去对如何以二维数组的形式访问该内存的理解:它实际上变成了一个指向 double 的指针.
In particular the two-dimensional array variable is a (single!) block of memory containing doubles which you can access with the [][]
syntax. This requires that the compiler know the dimension of the array, so that it can compute the correct offset to each element. It can also decay transparently to an pointer to that block of memory, but doing so loses the understanding of how to access that memory as a two dimensional array: it becomes effectively a pointer to double.
+----+ +---------+---------+---------+
| (a---------->) | a[0][0] | a[0][1] | a[0][2] | ...
+----+ +---------+---------+---------+
| a[1][0] | a[1][2] | ...
+---------+---------+
...
该函数期望的是一个指向内存块的指针,该内存块包含一个或多个指向包含双精度值的其他内存块的指针.
The thing expected by the function is a pointer to a block of memory which contains one or more pointers to additional blocks of memory containing doubles.
+---+ +------+ +---------+---------+
| p-------->| p[0]------->| p[0][0] | p[0][3] | ...
+---+ +------+ +---------+---------+
| p[1]--
+------+ +---------+---------+
... --->| p[1][0] | p[1][4] | ...
+---------+---------+
虽然语法看起来相似,但这两种结构的语义完全不同.
While the syntax looks similar, these two structures have totally different semantics.
有关更完整的讨论,请参阅 我的回答 对以前的问题(实际上是针对 c,但问题是相同的).
For a more complete discussion, see my answer to a previous questions (which actually address c, but the issues are the same).
相关文章