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?
To access nth element of array using pointer we use *(array_ptr + n) (where array_ptr points to 0th element of array, n is the nth element to access and nth element starts from 0).
A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creating a 2D integer pointer array of 5 rows and 5 columns. The element of the 2D array is been initialized by assigning the address of some other element.
The process begins by making a copy of the pointer that points to the array: int *ptr = A; // ptr now also points to the start of the array. This pointer points to the first element in the array.
If you want a pointer to a 3D array, you can do so with int (*p)[2][5][2]; p = &array; .
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With