Home > Blockchain >  In C, what does double asterisk ** in parameters of a function do
In C, what does double asterisk ** in parameters of a function do

Time:06-25

I came across a code snippet in linked list but this is the first time I see "**" double asterisk used in parameters. What does it do?

// Adding an item to the beginning of the list
void push(node_t ** head, int val) {
    node_t * new_node;
    new_node = (node_t *) malloc(sizeof(node_t));

    new_node->val = val;
    new_node->next = *head;
    *head = new_node;
}

CodePudding user response:

If you have a variable like for example

int x = 10;

and want to change it in a function you need to pass it to the function by reference.

In C passing by reference means passing a variable indirectly through a pointer to it. Thus dereferencing the pointer within the function you have a direct access to the original variable and can change it.

Here is a demonstration program.

#include <stdio.h>

void f( int *px )
{
    *px = 20;
}

int main( void )
{
    int x = 10;

    printf( "Before calling f x = %d\n", x );

    f( &x );

    printf( "After  calling f x = %d\n", x );
}

The program output is

Before calling f x = 10
After  calling f x = 20

If a variable has a pointer type like for example

node_t *head = NULL;

then again if you are going to change its value in a function you need to pass it to the function by reference as for example

push( &head, 10 );

So the corresponding function parameter will be declared like

void push(node_t ** head, int val);

And dereferencing the pointer to the original pointer head like

*head = new_node;

you can change the original pointer head defined in main.

If you will not pass the pointer by reference but pass it by value then the function will deal with a copy of the value of the original pointer. Changing the copy does not influence on the original pointer.

Consider the preceding demonstration program where the original variable is passed to the function by value

#include <stdio.h>

void f( int x )
{
    x = 20;
}

int main( void )
{
    int x = 10;

    printf( "Before calling f x = %d\n", x );

    f( x );

    printf( "After  calling f x = %d\n", x );
}

In this case the original variable x will not be changed. It is a copy of its value that was changed within the function. So the program output will be

Before calling f x = 10
After  calling f x = 10

CodePudding user response:

In this case, it declares a pointer to a node_t pointer, which is a function parameter.

Here is a simple example using character pointers:

char *charPointer = "This is a text.";
char **pointerToCharPointer = &charPointer;

printf("%s\n", charPointer);
(*pointerToCharPointer) = "This is something new.";
printf("%s\n", charPointer);

Output:

This is a text.
This is something new.
  • Related