Char (single letter) must be a pointer to correctl

2019-08-08 21:12发布

问题:

I've searched and maybe this is not even an issue but while working with chars in C (I'm working with X-Code on Mac) I'm having problems dealing with them unless I used pointers

int main(int argc, const char * argv[]){
    char myChar = "A";

    print("%c\n",myChar);
    print("%d\n",myChar);

    print("%c\n",65);
    print("%c\n",74);

    return 0;

}

So, simple stuff, but here's the output:

>J
>74

>A
>J

As you see, when I print myChar using %c, it gives me the lettre J and not A, same thing when I use %d, gives me 74 (char code for J) and not 65.

I also have a warning message on my variable declaration :

Incompatible pointer to integer conversion initializing char with an expression of type char[2]"

Which is kind of weird.

Now when replacing my code with this one :

int main(int argc, const char * argv[]){
    char *myChar = "A";

    print("%c\n",*myChar);
    print("%d\n",*myChar);

    print("%c\n",65);
    print("%c\n",74);

    return 0;

}

The output is as expected :

>A
>65

>A
>J

Any idea on what this behavior is due? Did I miss something or do I fail to understand something?

回答1:

In your code,

char myChar = "A";

is not correct. "A" is a string literal, which is not a fit for a char. You may want to write

 char myChar = 'A';

instead.

Note: Enable compiler warnings and pay heed to them.