cprintfc-stringsconversion-specifier

My program can't print a single-character string


I am trying to learn C, but for some reason my program doesn't want to print letters. It can print everything else like integers and floats just fine.

It doesn't give me an error as well, it just skips over the line where the character should be.

I tried simply printing out the letter "E" as a test, and it just printed out nothing.

#include <stdio.h>
int main()
{
int mynum = 6;
float myfloat = 3.14;
char* myletter = "E";


printf("%i\n",mynum);
printf("%f\n",myfloat);
printf("%c\n",myletter);
}

Solution

  • To output a string you need to use conversion specifier s instead of c

    printf("%s\n",myletter);
    

    Otherwise this call

    printf("%c\n",myletter);
    

    trying tp output a pointer as a character that invokes undefined behavior.

    If you want to output just the first character of the string literal then you should write

    printf("%c\n",*myletter);
    

    or

    printf("%c\n",myletter[0]);
    

    Pay attention to that the string literal "E" is stored in memory as a character array like

    { 'E', '\0' }