Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ** mean in C?

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?

like image 456
Brian Avatar asked Feb 10 '15 22:02

Brian


People also ask

What does two asterisks mean in C?

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.

What does * symbol mean in C?

Asterisk (*) − It is used to create a pointer variable.


3 Answers

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.

like image 33
Support Ukraine Avatar answered Sep 30 '22 19:09

Support Ukraine


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.

like image 80
Jonathan Wood Avatar answered Sep 30 '22 20:09

Jonathan Wood


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.

like image 36
imallett Avatar answered Sep 30 '22 20:09

imallett