there is a topic about this subject which is working with arrays but I can’t make it work with matrices.
(Topic: C++ array size dependent on function parameter causes compile errors)
In summary:
long rows, columns;
cin >> rows >> columns;
char *a = new char [rows];
compiles great in visual studio, but:
char **a = new char[rows][columns];
or
char *a[] = new char[rows][columns];
or
char *a[] = new char[rows][columns]();
or
char **a = new char[rows][columns]();
don’t compile at all.
Any help? Thank you
The array-new operator only allocates 1-dimensional arrays. There are different solutions, depending on what sort of array structure you want. For dimensions only known at runtime, you can either create an array of arrays:
or an array of elements with an associated array of pointers to the first element of each row (requiring just two hits to the memory allocator):
Either one will let you access matrix elements via
a[row][column].An alternate solution is to just use the one-dimensional array and generate indexes by hand:
This is probably faster than the double-indirection required in the first two solutions.
You could of course wrap this in a class to preserve a semblance of 2D indexing syntax: