NOTE: see the description below for how to do it. I will keep the original post as it is.
Original post
To make both sizes dynamic and sequential elements, you have no other way than your first method . ( note : see editing, there are ways to do this, but with g ++)
Think of it this way: when you tell the compiler to compute the array [i] [j], it will automatically translate it into:
*(array+i*m+j)
if the array is static and m (number of columns) is known. Or if the array is 2D (of type type ** ):
*(*(array+i)+j)
The second case is as you usually do with 2D arrays, but the data is NOT sequential. This leaves you with the first option. Now, in the first version, at compile time, you should know m . If you want m be set at runtime, the compiler simply cannot compute i*m+j .
Now there are ways around this. One of them is the use of classes, as you mentioned, that wrap around array = new type[n*m]; and correctly overload the operator [] . Another way to do this, which will require more memory (and therefore I personally do not recommend it), is to take a second array of type type ** and instead of setting each element to new type[m] , you set it to the beginning lines in your one-dimensional array.
However, the bottom line somewhere you should have new type[n*m]
Edit: methods for this using g ++
This came from the comments below:
type *array_helper = new type[n*m]; type (*array)[m] = (type (*)[m])array_helper;
Then you can use an array and the elements are sequential.
I tried this too and it worked
type array[n][m];
and I printed the addresses, in particular, the marked array[i][m-1] and array[i+1][0] , and the addresses are sequential.