本文介绍了malloced阵列VS.可变长度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方式来分配存储器给一个数组,它的大小是在开始时未知的。最常见的方式是使用的malloc 像这样

There are two ways to allocate memory to an array, of which the size is unknown at the beginning. The most common way is using malloc like this

int * array;
... // when we know the size
array = malloc(size*sizeof(int));

但它也有效的C99中定义阵列后,我们所知道的大小。

But it's valid too in C99 to define the array after we know the size.

... // when we know the size
int array[size];

他们是否绝对一样吗?

推荐答案

没有他们不是完全一样的。虽然这两个让你存储对象的相同数量和类型,请记住:

No they're not absolutely the same. While both let you store the same number and type of objects, keep in mind that:


  • 您可以免费() A malloced数组,但你不能免费()变长数组(虽然它超出范围后不再存在,一旦封闭块是左)。在技​​术术语,它们具有不同的存储时间的:分配的对相对的malloc的自动的变长数组

  • 虽然C有没有概念的的,许多实现分配从堆栈中一个可变长度的数组,而的malloc 在堆的。这是堆栈限制系统,例如一个问题许多嵌入式操作系统,其中该堆栈大小为KB的量级,而堆大得多。

  • 这也更容易测试失败的分配与的malloc 比可变长度的数组。

  • malloc内存的大小可以改变与的realloc(),而沃拉斯不能(更多precisely只能由具有不同的数组维再次执行该块可呈现失去了previous内容)。

  • 托管的C89实现只支持的malloc()

  • 托管的C11实现可能不支持变长数组(那么它必须定义 __ __ STDC_NO_VLA 作为根据C11 6.10.8.3整数1)。

  • 一切我已经错过了: - )

  • You can free() a malloced array, but you can't free() a variable length array (although it goes out of scope and ceases to exist once the enclosing block is left). In technical jargon, they have different storage duration: allocated for malloc versus automatic for variable length arrays.
  • Although C has no concept of a stack, many implementation allocate a variable length array from the stack, while malloc allocates from the heap. This is an issue on stack-limited systems, e.g. many embedded operating systems, where the stack size is on the order of kB, while the heap is much larger.
  • It is also easier to test for a failed allocation with malloc than with a variable length array.
  • malloced memory can be changed in size with realloc(), while VLAs can't (more precisely only by executing the block again with a different array dimension--which loses the previous contents).
  • A hosted C89 implementation only supports malloc().
  • A hosted C11 implementation may not support variable length arrays (it then must define __STDC_NO_VLA__ as the integer 1 according to C11 6.10.8.3).
  • Everything else I have missed :-)

这篇关于malloced阵列VS.可变长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:26