Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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' }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading