I have a concern about variable-length arrays. When I want to allocate an array dynamically, I'll get null, if it is not possible to allocate enough memory and I can respond to this properly in my program. With a variable length array I don't get this information. What should I do with this?

有帮助吗?

解决方案

You are right that VLA's are basically always unsafe. The only exception is if you ensure that you never make them larger than a size you would feel safe making a fixed-size array, and in that case you might as well just use a fixed-size array. There is one obscure class of recursive algorithms where VLA's could make the difference between being unable to solve the problem (stack overflow) and being able to, but for the most part, I would recommend never using VLA's.

That doesn't mean VLA types are useless, though. While VLA is bad/dangerous, pointer-to-VLA types are extremely useful. They make it possible to have dynamically-allocated (via malloc) multi-dimensional arrays without doing the dimension arithmetic manually, as in:

size_t n;
double (*matrix)[n] = malloc(n * sizeof *matrix);

to get an n-by-n matrix addressable as matrix[i][j].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top