Is it safe to use variable-length arrays?

后端 未结 1 1551
不思量自难忘°
不思量自难忘° 2020-11-27 06:30

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 respon

相关标签:
1条回答
  • 2020-11-27 07:02

    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].

    0 讨论(0)
提交回复
热议问题