In C, what does a variable declaration with two asterisks (**) mean?
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 hereprintf("%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);
C and C++ allows the use of pointers that point to pointers (say that five times fast). Take a look at the following code:
char a;char *b;char **c;a = 'Z';b = &a; // read as "address of a"c = &b; // read as "address of b"
The variable a
holds a character. The variable b
points to a location in memory that contains a character. The variable c
points to a location in memory that contains a pointer that points to a location in memory that contains a character.
Suppose that the variable a
stores its data at address 1000 (BEWARE: example memory locations are totally made up). Suppose that the variable b
stores its data at address 2000, and that the variable c
stores its data at address 3000. Given all of this, we have the following memory layout:
MEMORY LOCATION 1000 (variable a): 'Z'MEMORY LOCATION 2000 (variable b): 1000 <--- points to memory location 1000MEMORY LOCATION 3000 (variable c): 2000 <--- points to memory location 2000
It means that aPointer
points to a char pointer.
So
aPointer: pointer to char pointer*aPointer :pointer to char**aPointer: char
An example of its usage is creating a dynamic array of c strings
char **aPointer = (char**) malloc(num_strings);
aPointer gives you a char, which can be used to represent a zero-terminated string.
*aPointer = (char*)malloc( string_len + 1); //aPointer[0]*(aPointer + 1) = (char*)malloc( string_len + 1); //aPointer[1]