它是不好的做法,声明数组中端功能 [英] Is it bad practice to declare an array mid-function

查看:97
本文介绍了它是不好的做法,声明数组中端功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在努力只问我真正想找在这里......我真的只关心,如果它认为是不好的做法或者不声明数组像下面那里的大小可能会有所不同。如果是...我一般的malloc()代替。

 无效MyFunction的()
{    INT大小;    //做一堆东西
    大小= 10; //但本来是别的东西
    int数组【规格】;    //做更多的东西...}


解决方案

通常是的,这是不好的做法,虽然新标准,允许您使用此语法。在我看来,你必须分配(堆),你想使用并释放它一旦你用它做的内存。由于没有检查堆栈是否足以容纳数组,你应该使用一些方法,可以真正进行检查没有可移植的方法 - 样的malloc /释放calloc和放大器;自由。在嵌入式世界堆栈大小可能是一个问题。

如果你担心你的碎片可以创建自己的内存分配器,但是这是一个完全不同的故事。

in an effort to only ask what I'm really looking for here... I'm really only concerned if it's considered bad practice or not to declare an array like below where the size could vary. If it is... I would generally malloc() instead.

void MyFunction()
{

    int size;

    //do a bunch of stuff
    size = 10; //but could have been something else
    int array[size];

    //do more stuff...

}

解决方案

Generally yes, this is bad practice, although new standards allow you to use this syntax. In my opinion you must allocate (on the heap) the memory you want to use and release it once you're done with it. Since there is no portable way of checking if the stack is enough to hold that array you should use some methods that can really be checked - like malloc/calloc & free. In the embedded world stack size can be an issue.

If you are worried about fragmentation you can create your own memory allocator, but this is a totally different story.

这篇关于它是不好的做法,声明数组中端功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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