Click here to Skip to main content
14,971,553 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the difference between
double **a ;
a = new double *[M];

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

and how can translate it to C language

What I have tried:

Updated 2-Mar-18 15:08pm

1 solution

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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900