0

Why is it showing L if Iā€™m assigning it as %c and gives A if assigning %s?

https://code.sololearn.com/cRBXXZYh21te/?ref=app

28th Jan 2019, 3:09 PM
Hemabh Aditya
Hemabh Aditya - avatar
8 Answers
+ 3
As Julien Quentin said, you passed a memory address of a string, while printf function expected a char, as you had informed it, by specifying the "%c" format specifier. Down casting from memory address (64 bit) into char (8 bit) triggered the problem. That character wasn't even the letter 'L', it was a character by ASCII code of 192 (it does look a bit like a letter 'L' though). To understand this try: int x = (int)(char)ch1; printf("%d\n", x); It will output a negative value (in Code Playground it is -64), which is invalid for a char type whose value range lies between 0 to 255, it's out of range. To cope with that negative value, <x> will be incremented by 256, until its value lies within valid range (0-255). In this case, <x> (value is -64) is incremented by 256, becomes 192, thus the character of ASCII code 192 be printed. As a side note, if <x> value was above 255, <x> value will be decremented by 256 until it lies within valid range (0-255). Hth, cmiiw
28th Jan 2019, 7:11 PM
Ipang
+ 3
You are welcome Hemabh Aditya, glad if it helps. For future reference, please choose wisely a proper format specifier, depending on the variable type, for the printf function, though I understand you probably were doing that experiment for some curiosity of the code, nothing's wrong with that : ) Reference: [printf function] http://www.cplusplus.com/reference/cstdio/printf/ [Data type ranges] https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
29th Jan 2019, 9:23 AM
Ipang
+ 2
thanks both of you. your information helped me a lot.
29th Jan 2019, 6:45 AM
Hemabh Aditya
Hemabh Aditya - avatar
0
in case of %c why it is taking 8bits?
28th Jan 2019, 6:14 PM
Hemabh Aditya
Hemabh Aditya - avatar
0
iā€™m not clear about what you want to say. please explain properly.
28th Jan 2019, 6:30 PM
Hemabh Aditya
Hemabh Aditya - avatar