I have studied C pointers, and am wondering why the compiler is issuing an incompatible pointer types error in the following code:
#include <stdio.h>
const char *months(int n);
int main() {
char **p = months(2);
printf("%s", **p);
}
const char *months(int n) {
const char *m[] = {
"Invalid month",
"January",
"February",
"March",
"Aprli"
};
return (n == 0 || n > 12) ? m[0] : m[n];
}
I expect printf to display “February” as month, but I get that error
“Incompatible pointer types initializing ‘char **’ with an expression of type ‘const char *'”
during compile process .
If not wrong months function return pointer to “n” month. Next I create a pointer p to point the result of months function.
What is wrong here ?
pneeds to match the return type ofmonths, which isconst char *. This should work: