简体   繁体   English

如何在C ++中创建指向多维数组int的指针?

[英]How to create a pointer in C++ that points to a multidumentional array of int?

I know how to create a multidumentional array statndard way: 我知道如何创建一个多元数组标准方式:

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

And I know how to create a pointer that points to one dimentional array: 而且我知道如何创建指向一个维度数组的指针:

int * ms = new int[m];

But is it possible to create a pointer that points to multidumentional array? 但是有可能创建一个指向多重阵列的指针吗?

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

How to create such a pointer? 如何创建这样的指针?

The expression new int[m][n] creates an array[m] of array[n] of int . 表达式new int[m][n]创建new int[m][n]array[m] of array[n] of int new int[m][n]array[m] of array[n] of int Since it's an array new, the return type is converted to a pointer to the first element: pointer to array[n] of int . 由于它是一个新数组,因此返回类型将转换为指向第一个元素的pointer to array[n] of intpointer to array[n] of int Which is what you have to use: 这是你必须使用的:

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

Of course, you really shouldn't use array new at all. 当然,你真的不应该使用array new。 The _best_solution here is to write a simple Matrix class, using std::vector for the memory. 这里的_best_solution是编写一个简单的Matrix类,使用std::vector作为内存。 Depending on your feelings on the matter, you can either overload operator()( int i, int j ) and use (i, j) for indexing, or you can overload operator[]( int i ) to return a helper which defines operator[] to do the second indexation. 根据你对此事的感受,你可以重载operator()( int i, int j )和使用(i, j)进行索引,或者你可以重载operator[]( int i )来返回一个定义operator[]的帮助operator[]进行第二次索引。 (Hint: operator[] is defined on int* ; if you don't want to bother with bounds checking, etc., int* will do the job as the proxy.) (提示: operator[]int*上定义;如果你不想打扰边界检查等, int*将作为代理完成工作。)

Alternatively, something like: 或者,类似于:

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

will do the job, but in the long term, the Matrix class will be worth it. 将会完成这项工作,但从长远来看, Matrix课程将是值得的。

Sure, it's possible. 当然,这是可能的。

You'll be creating a pointer to a pointer to an int, and the syntax is just like it sounds: 你将创建一个指向int的指针,语法就像听起来一样:

int** ptr = sales;

You've probably seen more examples of this than you think as when people pass arrays of strings (like you do in argv in main()), you always are passing an array of an array of characters. 你可能已经看到了比你想象的更多的例子当人们传递字符串数组时(就像你在main()中的argv中那样),你总是传递一个字符数组的数组。

Of course we'd all prefer using std::string when possible :) 当然我们都喜欢在可能的情况下使用std :: string :)

I remember it was something like this: 我记得它是这样的:

int** array = new int*[m];
for(int i=0; i<m; i++) {
    array[i] = new int[n];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM