5

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?

Andrew
  • 24,218
  • 13
  • 61
  • 90
Green
  • 28,742
  • 61
  • 158
  • 247
  • 1
    possible duplicate of [How do I use arrays in C++?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – fredoverflow Aug 07 '12 at 15:40

3 Answers3

8

The expression new int[m][n] creates an 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. 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. The _best_solution here is to write a simple Matrix class, using std::vector for the memory. 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. (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.)

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
5

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

Of course we'd all prefer using std::string when possible :)

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
3

I remember it was something like this:

int** array = new int*[m];
for(int i=0; i<m; i++) {
    array[i] = new int[n];
}
sedran
  • 3,498
  • 3
  • 23
  • 39