2D数组与C ++ [英] 2D arrays with C++

查看:191
本文介绍了2D数组与C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数接受一个指针的指针作为参数。

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.

特别是二维数组变量是一个包含双精度的(单!)块的内存,您可以使用 [] [] 语法访问。这需要编译器知道数组的维度,以便它可以计算每个元素的正确偏移量。它也可以透明地衰减到指向该内存块的指针,但是这样做失去了如何作为二维数组访问该内存的理解:它实际上变为双指针。

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).

这篇关于2D数组与C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆