1

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);
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • You should use `%s` to print a nul terminated string. `printf("%c\n",myletter[0]);` will print the first character. – Retired Ninja Mar 16 '23 at 20:38
  • Does this answer your question? [Output single character in C](https://stackoverflow.com/questions/310032/output-single-character-in-c) (see this answer specifically: https://stackoverflow.com/a/310100) – mkrieger1 Mar 16 '23 at 20:40
  • "I am trying to learn C" --> Save time, enable all compiler warnings to get rapid feedback of bad code like `printf("%c\n",myletter);`. Certainly faster than posting on SO. – chux - Reinstate Monica Mar 16 '23 at 21:52

2 Answers2

3

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' }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

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);
tttony
  • 4,944
  • 4
  • 26
  • 41