What does '**' mean in C?

71,651

Solution 1

It is pointer to pointer.

For more details you can check: Pointer to pointer

It can be good, for example, for dynamically allocating multidimensional arrays:

Like:

#include <stdlib.h>

int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
    fprintf(stderr, "out of memory\n");
    exit or return
}

for(i = 0; i < nrows; i++)
{
    array[i] = malloc(ncolumns * sizeof(int));
    if(array[i] == NULL)
    {
        fprintf(stderr, "out of memory\n");
        exit or return
    }
}

Solution 2

In a declaration, it means it's a pointer to a pointer:

int **x;  // declare x as a pointer to a pointer to an int

When using it, it deferences it twice:

int x = 1;
int *y = &x;  // declare y as a pointer to x
int **z = &y;  // declare z as a pointer to y
**z = 2;  // sets the thing pointed to (the thing pointed to by z) to 2
          // i.e., sets x to 2

Solution 3

Pointer to a pointer when declaring the variable.

Double pointer de-reference when used outside the declaration.

Solution 4

It means that the variable is a pointer to a pointer.

Solution 5

You can use cdecl to explain C-types.

There's an online interface here: http://cdecl.org/. Enter "int **x" into the text field and check the result.

Share:
71,651
numerical25
Author by

numerical25

Updated on January 02, 2021

Comments

  • numerical25
    numerical25 over 3 years

    What does it mean when an object has two asterisks at the beginning?

    **variable
    
  • Adam Rosenfield
    Adam Rosenfield almost 14 years
    It would also be a good idea to demonstrate properly freeing the multidimensional array in reverse order of allocation.
  • Incognito
    Incognito almost 14 years
    Yes you are right :). Not forget to use for(int i = 0; i < nrows; i++) free(array[i]); free(array); to free allocated memory.
  • numerical25
    numerical25 almost 14 years
    And what if you were to set z to 2 using just one point *z = 2 ??
  • numerical25
    numerical25 almost 14 years
    Thank you. That link was the most beneficial.
  • Michael Mrozek
    Michael Mrozek almost 14 years
    @num It would change y to point to the memory location 2, and *y = 1; or **z = 1; would both try to change the memory at address 2, which is almost certainly outside the legal range you've been allocated
  • agf
    agf about 12 years
    If he's asking a question this basic, he probably needs the concept of a pointer explained, too.