The operator * is used for dereferencing and the operator & is used to get the address (can be called reference in general sense). These operators cancel effect of each other when used one after another. We can apply them alternatively any no. of times.
Based on above information, predict the output of below program:
#include <stdio.h>
int main() {
char *ptr = "geeksforgeeks";
printf("%c\n", *&*&*ptr);
getchar();
return 0;
}
Output
g
Explanation: The expression *&*&*ptr dereferences ptr to get the character 'g' from the string "geeksforgeeks". First, ptr is dereferenced to get 'g', then address is obtained returning ptr. Again, it is dereferenced returning 'g' and then address is determined returing ptr. Finally, it is dereferenced to obtain 'g'. Therefore, the program prints 'g'.
Now try predicting the output of the below:
#include <stdio.h>
int main() {
char *ptr = "geeksforgeeks";
printf("%s\n", *&*&ptr);
getchar();
return 0;
}
Output
geeksforgeeks
Explanation: The expression *&*&ptr is equivalent to just ptr in this code. It first dereferences ptr to get the string "geeksforgeeks", then takes its address and dereferences it again, ultimately returning the original address stored in ptr. Therefore, the program prints "geeksforgeeks".