I have a sample C
program I am trying to understand. Below is a function excerpt from the source code:
double** Make2DDoubleArray(int arraySizeX, int arraySizeY)
{
double** theArray;
theArray = (double**) malloc(arraySizeX*sizeof(double*));
int i = 0;
for (i = 0; i < arraySizeX; i++)
theArray[i] = (double*) malloc(arraySizeY*sizeof(double));
return theArray;
}
My question is what is the significance of the **
in the return type. I know that the *
is generally used as a pointer
. I know that it may also be used to dereference
the pointer.
This makes me think that double**
is a double value because it is essentially the dereferencing of a reference. Is my thinking correct? If not, can someone please explain the use of **
in this example?
C syntax is rather logical. As an asterisk before the identifier in the declaration means pointer to the type of the variable, two asterisks mean pointer to a pointer to the type of the variable. In this case array is a pointer to a pointer to integers. There are several usages of double pointers.
Asterisk (*) − It is used to create a pointer variable.
some_type*
is a pointer to some_type. So
some_type**
is a pointer to a pointer to some_type.
One typically use is for (emulating) 2D arrays.
In your case the first malloc reserves memory for the pointers to an array of doubles. The second malloc reserves memory for an array of doubles. In this way you have allocated memory that can be used like a 2D array.
In this case, double
means a variable of type double.
double*
means a pointer to a double variable.
double**
means a pointer to a pointer to a double variable.
In the case of the function you posted, it is used to create a sort of two-dimensional array of doubles. That is, a pointer to an array of double pointers, and each of those pointers points to an array of pointers.
Here's a more general answer: the spiral rule. For this particular example:
+-----------+
|+--------+ |
|| +---+ | |
|| ^ | | |
double** foo; | | |
^ |^ | | |
| |+------+ | |
| +---------+ |
+--------------+
Read this as "\"foo\" is a pointer to a pointer to a double
."
In this case, each pointer is semantically an array, so this represents a 2D array of type double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With