本文介绍了VLA 和通过 malloc 进行动态内存分配有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此很好奇:
有什么区别:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
和:
char Buffer[MAX_BUF];
推荐答案
案例 1:在
Case 1: In
char Buffer[MAX_BUF];
Buffer
是一个数组,大小为MAX_BUF
.分配技术称为VLA.Buffer
is an array of sizeMAX_BUF
. The allocation technique is called VLA.案例 2:在
const int MAX_BUF = 1000; char* Buffer = malloc(MAX_BUF);
Buffer
是一个指针,它被分配了一个MAX_BUF
大小的内存,它是1000
.Buffer
is a pointer which is allocated a memory of sizeMAX_BUF
which is1000
.并且,数组与指针不相同,并且C-FAQ 有一个很好的集合,详细说明了原因.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
在可用性和行为方面的主要区别是:
The major difference, in terms of usability and behaviour are:
- (1) 在堆栈上,通常 ,而 (2) 在堆上,总是.
- (1) 分配后大小固定,(2) 可以调整大小.
- (1) 在调用封闭函数时分配并且具有块作用域 OTOH,(2) 在运行时动态分配内存,并且返回的内存具有从分配到释放的生命周期.
- (1) 分配的内存不需要由程序员管理,而在(2) 中所有
malloc()
d 的内存应该是free()
d.
- (1) is on stack, usually , while (2) is on heap, always.
- (1) has fixed size once allocated, (2) can be resized.
- (1) is allocated when the enclosing function is called and has the block scope OTOH, (2) is allocated memory dynamically, at runtime and the returned memory has a lifetime which extends from the allocation until the deallocation.
- (1) allocated memory need not be managed by programmer, while in (2) all
malloc()
d memory should befree()
d.
这篇关于VLA 和通过 malloc 进行动态内存分配有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!