tags:

views:

98

answers:

4

I am currently reading some C++ source code, and I came across this:

 double **out;
 // ... lots of code here 

 // allocate memory for output of each neuron
 out = new double*[num];

Not entirely sure what it does, or what it means. Is it a pointer... is at an array?

There is also the following:

 // vector of weights for each neuron
 double ***weight;

 // allocate memory for weights
 weight = new double**[numl];

I am quite confused :P, any help is appreciated.

+2  A: 

It's a pointer to pointer to double. Or array of pointers to double. Or if every pointer itself allocates array it might be a matrix.

out = new double*[num]; // array of pointers

Now it depents if out[0] is allocated like this:

out[0] = new double; // one double

or like this:

out[0] = new double[num]; // now you've got a matrix
Nikola Smiljanić
+6  A: 

new double*[num] is an array of double pointers i.e. each element of the array is a double*. You can allocate memory for each element using out[i] = new double; Similarly weight is an array of double**. You can allocate the memory for each weight element using new double*[num] (if it is supposed to be an array of double*)

Naveen
Thanks for the help
Daniel
+1, best answer. However, separately allocating every `double` is probably not a good idea, especially for a scientific application. Better to allocate one flat array of doubles, and have all the pointers point to elements of that array.
Potatoswatter
+1  A: 

Actually, writing

double*[] out;

is in C/C++ equal to

double** out;

and it means an array of pointers to double. Or a pointer to pointers of double. Because an array is nothing more than just a pointer. So this is in essence a two-dimensional array.

You could as well write

double[][] out;

And likewise, adding another pointer level, will add another dimension to your array. So

double ***weight;

is actually a pointer to a three-dimensional array.

nathanvda
No. `double*[] out;` is a syntax error. `double* out[];` would declare an array of `double*`, not a pointer. Arrays and pointers are distinct types; for example, you can't assign to an array, so `out = new double*[num];` would be invalid.
Mike Seymour
+1  A: 

Basically both of your code fragments allocate array of pointers. For allocation it does not matters to what. Correct declaration is needed only for type checks. Square bracjets should be read separately and means only it is array.

Consider following code as quick example:

#include <stdio.h>

int main()
{
    unsigned num = 10;
    double **p1, ***p2;

    p1 = new double*[num];
    p2 = new double**[num];

    printf("%d\n", sizeof(p1));
    printf("%d\n", sizeof(p2));

    delete [] p1;
    delete [] p2;

    return 0;
}

Yes, both are just pointers. And memory allocated is sizeof(double*) * num.

Roman Nikitchenko