Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, what does a variable declaration with two asterisks (**) mean?

Tags:

c

pointers

I am working with C and I'm a bit rusty. I am aware that * has three uses:

  1. Declaring a pointer.
  2. Dereferencing a pointer.
  3. Multiplication

However, what does it mean when there are two asterisks (**) before a variable declaration:

char **aPointer = ... 

Thanks,

Scott

like image 852
Scott Davies Avatar asked Nov 30 '10 21:11

Scott Davies


People also ask

What does * mean after a variable in C?

When used with an already declared variable, the asterisk will dereference the pointer value, following it to the pointed-to place in memory, and allowing the value stored there to be assigned or retrieved.

What does two stars mean in C?

One star means a pointer. Two stars mean a pointer to a pointer.

What does asterisks mean in C?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value. In the C programming language, the deference operator is denoted with an asterisk (*).

What does the * mean in pointers?

The asterisk * used to declare a pointer is the same asterisk used for multiplication.


1 Answers

It declares a pointer to a char pointer.

The usage of such a pointer would be to do such things like:

void setCharPointerToX(char ** character) {    *character = "x"; //using the dereference operator (*) to get the value that character points to (in this case a char pointer } char *y; setCharPointerToX(&y); //using the address-of (&) operator here printf("%s", y); //x 

Here's another example:

char *original = "awesomeness"; char **pointer_to_original = &original; (*pointer_to_original) = "is awesome"; printf("%s", original); //is awesome 

Use of ** with arrays:

char** array = malloc(sizeof(*array) * 2); //2 elements  (*array) = "Hey"; //equivalent to array[0] *(array + 1) = "There";  //array[1]  printf("%s", array[1]); //outputs There 

The [] operator on arrays does essentially pointer arithmetic on the front pointer, so, the way array[1] would be evaluated is as follows:

array[1] == *(array + 1); 

This is one of the reasons why array indices start from 0, because:

array[0] == *(array + 0) == *(array); 
like image 123
Jacob Relkin Avatar answered Oct 16 '22 20:10

Jacob Relkin