C ++语言中的动态内存分配 [英] Dynamic memory allocation in C++ language

查看:87
本文介绍了C ++语言中的动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



-

What is the difference between
-

double **a ;
    
a = new double *[M];






and

for (int i = 0; i < M; i++) {
a[i] = new double [N];} 





和怎么能把它翻译成C语言



我尝试过:



-----------------------------------



and how can translate it to C language

What I have tried:

-----------------------------------

推荐答案

第一个分配一个指向大小为M的双精度指针数组并将其分配给a。

第二个加载数组a,其中M个数组为N个大小为N.



双星号表示你有一个二维的双精度数组。这些代码片段实际上是分配2D数组所涉及的两个步骤。



new转换为C语言中的malloc或calloc。我更喜欢calloc。还要记住,在C ++中你用删除释放对象,而在C中你用free。



习惯上,每次你编写一个分配例程,就像那些,还写了相应的释放例程。您必须保持同步才能正确释放内存。这是导致错误的更常见原因之一,所以如果你采用这种习惯,你会省去很多头痛和浪费时间。
The first allocates an array of pointers to doubles of size M and assigns it to a.
The second loads the array a with M arrays of doubles of size N.

The double asterisk indicates you have a two dimensional array of doubles. Those code fragments are actually the two steps involved in allocating a 2D array.

new translates to malloc or calloc in the C language. I prefer calloc. Also remember that in C++ you release objects with delete and in C you use free.

As a matter of habit, every time you write an allocation routine, like those, also write a corresponding deallocation routine. You have to keep them in synch in order to release memory correctly. That is one of the more common causes of errors so if you adopt this habit you will save yourself a lot of headache and wasted time.


这篇关于C ++语言中的动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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