by simias · 13y ago · 0 comments
Can you give us a practical example of some code where variable-length arrays prove really useful?
1. Multidimensional arrays where the sizes are quasi-fixed but not known at compile time. Comes up in various kinds of grid-simulation code, for example. You could malloc() in this case, but then you lose the notational convenience of 2d arrays.
2. Refactoring code that uses #define'd constants, to take runtime instead of compile-time parameters. For example, a common first-pass to said grid-simulation code is to have some WIDTH and HEIGHT magic numbers, which you might later regret and want to make into command-line parameters. Refactoring is trivial if you have VLAs.
It also seems cleaner (to me) semantically. I can see why, implementation-wise, classic C auto arrays required constant sizes. But from a slightly higher-level perspective, whether a variable is auto or not, and whether its size is a compile-time constant or not, feel like independent decisions. It feels particularly messy that you have different notation for arrays whose sizes are known at compile time; the syntactic sugar there has some rough edges. I also find it cleaner if explicit malloc()s are used only when something beyond boilerplate is going on, letting the compiler handle the boilerplate case of allocating/deallocating a conceptually block-scoped array of size N.
void func(int M, int N, int P, double *a_flat) {
double (*a)[N][P] = (double (*)[N][P])a_flat;
// use a[i+1][j+2][k-1] instead of a_flat[((i+1)*N+(j+2))*P+k-1].There are also some possible applications here: http://gustedt.wordpress.com/2011/01/13/vla-as-function-argu...
In fairness, I've used them only rarely, but those few times I've used them have saved me a bit of grief.
I could easily live without them if required...