5

我知道如何创建一个多维度数组标准方式:

const int m = 12;
const int y = 3;
int sales[y][n];

而且我知道如何创建一个指向一维数组的指针:

int * ms = new int[m];

但是是否可以创建一个指向多维数组的指针?

int * sales = new int[y][m];   // doesn't work
int * mSales = new int[m];    // ok
int * ySales = new int[y];    // ok
mSales * ySales = new mSales[y];    // doesn't work, mSales is not a type

如何创建这样的指针?

4

3 回答 3

8

该表达式new int[m][n]创建一个array[m] of array[n] of int. 由于它是一个新数组,因此返回类型被转换为指向第一个元素的指针:pointer to array[n] of int。这是你必须使用的:

int (*sales)[n] = new int[m][n];

当然,你真的不应该使用 array new 。这里的_best_solution是写一个简单的Matrix类, std::vector用于内存。根据您对此事的感受,您可以重载operator()( int i, int j )(i, j) 用于索引,或者您可以重载operator[]( int i )以返回定义operator[]进行第二次索引的帮助器。(提示: operator[]在 上定义int*;如果您不想打扰边界检查等,int*将作为代理完成工作。)

或者,类似:

std::vector<std::vector<int> > sales( m, n );

会做这项工作,但从长远来看,这Matrix门课是值得的。

于 2012-08-07T13:34:25.603 回答
5

当然,这是可能的。

您将创建一个指向 int 指针的指针,语法就像听起来一样:

int** ptr = sales;

你可能看到的例子比你想象的要多,因为当人们传递字符串数组时(就像你在 main() 中的 argv 中所做的那样),你总是传递一个字符数组的数组。

当然,我们都希望尽可能使用 std::string :)

于 2012-08-07T13:13:00.620 回答
3

我记得是这样的:

int** array = new int*[m];
for(int i=0; i<m; i++) {
    array[i] = new int[n];
}
于 2012-08-07T13:14:12.720 回答