On 2 dimensional array of C++

To allocate a 2-d array on the stack, a C-style array is

int d;

Then to refer to an element it is like

d[i][j];

To make a dynamical allocation, one can NOT write his code like this

int **wrong_d = new int;

since the d in int d; is not a int**, instead it is of the type

int (*)

or in your evil human words, it is a int pointer.

It is a little tricky to declare a 2-d array dynamically.

int (*d) = new int;

Or

int v1 = 2;
int (*d) = new int[v1];

The number 3 here can NOT be replace by a non-constant. My understanding is that since this value is associated with the type of d, in a strong type language like C/C++ which should be known by the compiler.

We can check the size of variables to verify this interpretation.

1 #include
2
3 using namespace std;
4
5 int main(int argc, char **argv)
6 {
7     int v1 = 2;
8     int (*d) = new int[v1];
9     cout << "sizeof(d): " << sizeof(d) << endl;
10     cout << "sizeof(d): " << sizeof(d) << endl;
11     cout << "sizeof(d): " << sizeof(d) << endl;
12     cout << "sizeof(d): " << sizeof(d) << endl;
13     return 0;
14 }

The output is:

\$./test
sizeof(d): 8        //< 2 pointers, &d and &d
sizeof(d): 12    //< int, d d d
sizeof(d): 12    //< int, d d d
sizeof(d): 4  //< an integer

To save your life, I would recommend to use vectors.

int v1 = 2;
int v2 = 3;
vector > d(v1, vector(v2, 0));
1. 2. • • 