pr1m3x
pr1m3x

Reputation: 2087

Why am I getting an incompatible pointer types error?

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 ?

Upvotes: 2

Views: 10307

Answers (5)

unwind
unwind

Reputation: 399803

You can't have a "pointer to point at the result" without storing the result somewhere, you're trying to store the result (which is char *) in a variable of type char * * and that doesn't work.

You need:

char *result = (char *) month();
char **p = &result;

Also, you should make the m vector static, since it's a bit gross to return a pointer to a local variable of a function.

I added the cast since you're dropping the constness, which is also a bit ugly but I didn't want to change it around too much.

Upvotes: 5

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16597

Try this!

#include <stdio.h>

const char *months(int n); 

int main(void) 
{
    const char *p = months(2);
    printf("%s \n", p); 
    return 0;
}

const char *months(int n)  
{
    const char *m[] = { 
        "Invalid month",
        "January",
        "February",
        "March",
        "Aprli"
    };  
    return (n == 0 || n > 12) ? m[0] : m[n];
}

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258588

const char *months

this returns a const char*

char **p = months(2);

this tries to convert a const char* to a char**.

What's wrong is the conversion.

The correct way would be

const char *p = months(2);

Upvotes: 0

Linus Kleen
Linus Kleen

Reputation: 34632

p needs to match the return type of months, which is const char *. This should work:

const char *p = months(2);
printf("%s", p);  // no need to dereference to *p here

Upvotes: 4

ouah
ouah

Reputation: 145829

char **p = months(2);

should be

const char *p = month(2);

because your month function returns a const char * and not a char **.

and

printf("%s", **p);

should be

printf("%s", p);

because p is the pointer to your string.

Upvotes: 1

Related Questions