In Java, one can do the following: int[][] array = {{1,2,1}, {1},
{0,0,0,0,0,0,0,-1}};
How can one declare such array in C++/C without using various new
operators individually to each row indicies? (with a ptr-ptr)
Also, I've noticed that it works for char[][] array:
char *charArray[] = {"123456", "1515", "1"}; compiles on mingw32
but
int *intArray[] = {{1,2,1,2,1}, {11}, {0}}; wouldn't compile.
...
It all depends on what it is you really need. What do you mean by "different row
lengths" and why do you need it?
If you are trying to save memory, i.e. make a sparse 2D array to consume the
amount of memory determined by the number of actually used elements, not by the
product of its maximum dimensions (m*n), then what you called 'ptr-ptr' might be
the way to go. The row arrays are not required to be allocated by 'new' though.
Your example with 'charArray' is nothing else then an implicit ptr-ptr construct
with row arrays (string literals) allocated in static memory. You can achieve
something similar with 'intArray' as well, but since there's no int-array
literals in C++, the row arrays will have to be declared explicitly:
int row1[] = { 1, 2, 1, 2, 1};
int row2[] = { 11 };
int row3[] = { 0 };
int* intArray[] = { row1, row2, row3 };
The row arrays and the 'intArray' itself can be placed in static, automatic or
dynamic ('new'-ed) memory, depending on what you need.
Of course, if you don't really care to save memory and just want to have
variable-length array initializers in your source code, you can do what Markus
suggested, i.e. use an ordinary 2D array and specify the row length explicitly
int intArray[][5] = {
{ 1, 2, 1, 2, 1 },
{ 11 },
{ 0 }
};