As others have pointed out, VLAs simplify stack overflows. I am not a compiler writer, but I understand that VLA can also be a fake for support (now they become optional in C2011). And their use is limited to the area of ββblocks or functions; you cannot use VLAs in the file area, and they cannot have external binding.
I would not want the VLA syntax to go away though; this is very convenient for the dynamic distribution of multidimensional arrays, where the internal dimensions are unknown until runtime, for example:
size_t r, c; // get values for r and c int (*arr)[c] = malloc(r * sizeof *arr); if (arr) { ... arr[i][j] = ...; ... free(arr); }
One contiguous distribution (and one corresponding free ), and I can fine-tune it as a 2D array. Alternatives usually mean splitting in parts:
size_t r, c; ... int **arr = malloc(sizeof *arr * r); if (arr) { for (i = 0; i < c; i++) arr[i] = malloc(sizeof *arr[i] * c); ... arr[i][j] = ...; ... for (i = 0; i < c; i++) free(arr[i]); free(arr); }
or using 1-dimensional offsets:
int *arr = malloc(sizeof *arr * r * c); if (arr) { ... arr[i * r + j] = ...; ... free(arr); }
John bode
source share