error when printing special characters in C. The problem is %c vs %s

Viewed 373

I'm starting with C, I have found a little difference between %c and %s, when must print special characters. I dont know if I'm doing something wrong, or it's a C limitation:

unsigned char str1[]="á";

printf("str1 c (%c)\n", str1[0]);
printf("str1 s (%s)\n", &str1[0]);

unsigned char str2[]="áéíóúñ";
printf("str2 s (%s)\n", str2);

And the output is:

str1 c ( )
str1 s (á)
str2 s (áéíóúñ)

In conclusion: when I try write special characters with %c, I cannot see it.

2 Answers

The %c format string for printf causes the corresponding argument to be converted to and interpreted as an unsigned char. An unsigned char is 1 byte long. One byte from your non-ASCII string does not necessarily correspond to anything you would recognize as a character.

It is likely that your editor, which you used to place some representation of those strings into your source code, encodes the two strings with some Unicode encoding scheme. This SO answer has some information to get you started on dealing with Unicode in C.

The reason things work fine with the %s formatting string is that printf will just start dumping out bytes until it hits the null byte terminator. Your output terminal is probably set to the same encoding scheme as your editor, so it's able to correctly interpret those bytes the way you intended.

Ok, now I understand it.

If I write:

unsigned char str3[]="a";
printf("%d\n", strlen((char *)str3));

The output is:

1

But I write:

unsigned char str1[]="á";
printf("%d\n", strlen((char *)str1));

The output is:

2

I understood that the character sizes can be 1, or 2 if are special characters , no?

Related