Hello all,
I have very basic question on intializing two dimenstional array. Why cant I
initialize a two dimensional int array like the following ?
int **intArray = new int[10][20]
What is the best way to intialize such array if I need to pass the size as
variables, like int [rows][columns], where rows and columns has the size of the
array.
Thanks in advance
Drak
Scott Meyers has a nice chapter on implementing a 2-dimensional array
class in "More Effective C++", item 30: "Proxy classes".
However, you can also use a vector of vectors instead of unsafe
arrays. Note that vectors -- unlike arrays -- can also be dynamically
sized, so this is what you need if your dimensions aren't known at
compile time.
// e.g.:
#include <iostream>
#include <ostream>
#include <vector>
typedef std::vector<int> IntVec;
typedef std::vector<IntVec> IntArray2D;
const int IDX_1 = 10;
const int IDX_2 = 20;
int main() {
using std::cout;
using std::endl;
IntVec dummy(IDX_2); // reserving space in the ctor
IntArray2D x(IDX_1); // avoids unnecessary reallocations
int c=0;
for (int i=0; i<IDX_1; ++i) {
for (int j=0; j<IDX_2; ++j, c++)
dummy[j] = (c);
x
= dummy;
}
for (int i=0; i<IDX_1; ++i) {
cout << "x[" << i << "]:";
for (int j=0; j<IDX_2; ++j)
cout << " " << x[j];
cout << endl;
}
return 0;
}
I'm not sure how to reserve enough space up front for IntArray2D,
though; assigning directly to x[j] instead of filling up the dummy
will compile, but then gives me an access violation at run-time. The
use of a temporary vector<int> (i.e. "dummy") seems necessary in order
for it to work.
Once the 2D-vector has been initialized, it should not be a problem to
assign directly using just the index values.