My program can't print a single-character string

68 Views Asked by At

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);
}
2

There are 2 best solutions below

0
Vlad from Moscow On BEST ANSWER

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' }
0
tttony On

To print a character you do it like this:

char myletter = 'E'; // <-- Note the single quotes and is not a pointer
printf("%c\n",myletter);

To print a string:

char *myletter = "E"; // <-- Note the double quotes
printf("%s\n",myletter);