I am reading C The Complete Reference 4th edition by Herbert Schildt. In Chapter 4 - Arrays and Strings, it mentions "One major reason for the addition of variable-length arrays to C99 is to support numeric processing".
My question is: What is numeric processing? And how do variable-length arrays support numeric processing?
There are three places where variable-length arrays can appear:
Automatic local variables can be problematic — they occupy stack space, and there's no portable way to find out whether there's enough stack space left to allocate the array you want to create. If there isn't enough space, the program will halt unilaterally; there is no way to recover from the error. This has many people up in arms against VLAs.
Dynamically allocated arrays are not problematic — though the notation is not singularly convenient. You can tell when an allocation fails and react appropriately.
Function parameters are where the flexibility comes into play — especially with 2D arrays (and higher dimensions too).
Prior to the introduction of VLAs, you had to either treat the array as a 1D vector and calculate the indexes manually or you had to write different functions for each different size of matrix — or, at least, for each different number of columns.
You could use:
That's fine as far as it goes, but if you want matrices with different numbers of columns, you have to write (and call) different functions.
An alternative was to use a large 1D vector and calculate the 2D subscripts in your code:
With VLA notation for the arguments, though, you can write a single function to print any 2D matrix (of a given base type) and use direct subscript notation for maximum convenience:
There isn't much difference in the notation, but the gain in flexibility is enormous. You can write a single matrix multiplication function that will work for any sizes of matrix, for example, whereas before VLAs were available, only the 1D version could deal with arbitrary sizes of array.
The dynamic allocation is reasonably simple, though not entirely obvious:
Output:
And the VLA notation can be used with fixed-size arrays — global or local — too. That is, ordinary arrays can be passed to functions that accept a VLA as long as you describe the arrays accurately:
Output: