malloc数组和常规数组有什么区别

malloc数组和常规数组有什么区别

本文介绍了当我必须指定内存大小时,malloc数组和常规数组有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在malloc() -ed数组和常规数组之间,我必须指定内存大小时,有什么区别

What is the difference between malloc()-ed array and regular array when in both I have to specify memory size, for example

char* arr =  malloc(50 * sizeof(char))

vs

int arr [50]

推荐答案

嗯,差异太多了.首先,请阅读 数组不是指针,反之亦然 .

Well, there are too many differences. To start with, read about arrays are not pointers and vice versa.

也就是说,从可用性角度(我认为您对此感兴趣的 )来看,三个主要区别

That said, three major differences from the usability point of view (which I feel you're interested about)

  • 一个数组的范围仅限于其封闭块,但是动态分配的内存是活动的,除非手动释放.因此,无法对函数本地的数组进行retrun运算,而可以对通过malloc() -ing返回的指针进行运算.

  • An array has a scope limited to its enclosing block, but dynamically allocated memories live unless deallocated manually. So, arrays local to a function cannot be retruned but a pointer, returned via malloc()-ing , can be.

对于非 VLA 的情况,数组大小必须是编译时间常数,但在运行时指定malloc()大小.换句话说,对于数组,您需要在编译时知道大小,而对于malloc() -ing,则完全有可能在运行时确定请求的大小.

For non-VLA case, array size must be a compile time constant but for malloc() size is specified at runtime. In other words, for arrays, you need to know the size at compile time whereas, for malloc()-ing, it's perfectly possible to determine the requested size at runtime.

无法调整数组大小.定义后,它们将使用其大小所需的所有内存. OTOH是malloc() -ed指针,指向一定数量的内存,可以根据需要很好地realloc() -ed指向其他一定数量的内存.

Arrays cannot be re-sized. Once defined, they use all the memory required for their size. OTOH, a malloc()-ed pointer, pointing to some amount of memory, can very well be realloc()-ed to some other amount of memory, as needed.

这篇关于当我必须指定内存大小时,malloc数组和常规数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:03