I am working with C and I'm a bit rusty. I am aware that *
has three uses:
However, what does it mean when there are two asterisks (**
) before a variable declaration:
char **aPointer = ...
Thanks,
Scott
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.
One star means a pointer. Two stars mean a pointer to a pointer.
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 (*).
The asterisk * used to declare a pointer is the same asterisk used for multiplication.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With