它是安全使用变长数组? [英] Is it safe to use variable-length arrays?

查看:106
本文介绍了它是安全使用变长数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于变长数组关注。当我要动态分配一个数组,我会得到空,如果它是不可能分配足够的内存,我可以向这个正确的在我的计划作出回应。具有可变长度数组我没有得到这个信息。我应该怎样做呢?

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?

推荐答案

您是正确的,VLA的基本上都是不安全的始终。唯一的例外是,如果你确保你永远不会让他们比大小,你会感到安全作出固定大小的数组大,在这种情况下,你可能也只是使用一个固定大小的数组。有一个不起眼的类的递归算法,其中VLA的可能使暂时无法解决问题(堆栈溢出),并能够,但在大多数情况下,我会建议使用从未VLA的之间的区别。

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.

这并不意味着VLA类型是无用的,虽然。虽然VLA是坏/危险的指针到VLA 的类型是非常有用的。他们使人们有可能是动态分配的(通过的malloc )多维数组无需手动做算术的尺寸,如:

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);

获得一个正由n矩阵寻址为矩阵[i] [j]的

这篇关于它是安全使用变长数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆