In C++ I’d like to do something like:
int n = get_int_from_user(); char* matrix = new char[n][n]; matrix[0][0] = 'c'; //... matrix[n][n] = 'a'; delete [][] matrix;
but of course this doesn’t work. What is the best way to do something similar? I’ve seen some solutions to this but they seem pretty messy.
The manual dynamic way:
Let’s say you want an array of width*height, the most efficient way is to just use a single dimensional array:
To delete it:
To access it:
To modify it:
Boost Matrix:
Consider using boost::matrix if you can have the dependency.
You could then tie into the boost linear algebra libraries.
Here is some sample code of boost::matrix:
On the stack for some compilers:
Some compilers actually allow you to create arrays on the stack with runtime determined sizes. g++ is an example of such a compiler. You cannot do this by default VC++ though.
So in g++ this is valid code:
Drew Hall mentioned that this C99 feature is called Variable Length Arrays (VLAs) and it can probably be turned on in any modern compiler.