1

So this is the code

void main()
{
  unsigned char n,t;
  scanf("%hhu %hhu",&n,&t);
  printf("%hhu %hhu",n,t);
}

The problem is when I input 5 and 1 respectively, the output is 0 and 1. 0 for n and 1 for t. However, when I changed the type from char to int/unsigned, the output is right as expected: 5 and 1.

The question is why asking for (number) input with char gives invalid value?

  • What are you trying to achieve with this? `scanf` is expecting `unsigned char*` with these formatting strings, is this intended? – bash.d Apr 04 '13 at 08:53
  • 1
    example program does not give the incorrect output you describe for me ( gcc on Ubuntu 12.04 ) – Vorsprung Apr 04 '13 at 08:56
  • May I ask which on platfrom you experience this behaviour? – alk Apr 04 '13 at 09:19
  • @bash.d (CMIIW) In addition to store a character, _char_ can be used to save 1 byte of number (-127..128 or 0..255) right? I'm just trying it for fun, and then I'm curious about the error –  Apr 04 '13 at 10:29
  • Alright! There you go – bash.d Apr 04 '13 at 10:31
  • @Vorsprung Windows 7 x64 Codeblocks 12.11 (GCC 4.7.1) http://i.imgur.com/TldzKaX.png –  Apr 04 '13 at 10:37
  • @Alk Windows 7 x64 Codeblocks 12.11 (GCC 4.7.1) http://i.imgur.com/TldzKaX.png –  Apr 04 '13 at 10:37
  • This might answer the question: http://stackoverflow.com/a/15825386/694576 – alk Apr 05 '13 at 07:19

2 Answers2

3

int main(void) please

scanf("%hhu %hhu",&n,&t);

here ---------- ^ ------^ unsigned char * is expected

same for printf("%hhu %hhu",n,t);

so change

char n,t;

to

unsigned char n,t;

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 3
    The first line alone would have been enough to get my upvote ;-) –  Apr 04 '13 at 09:09
  • http://ideone.com/A38Ze5, In your picture you are still using main in a wrong way, and you don't include stdio – David Ranieri Apr 04 '13 at 10:52
  • If it still doesn't work replace `printf("%hhu %hhu",n,t);` with `printf("%hhu %hhu\n",n,t);` (note the \n at the end) – David Ranieri Apr 04 '13 at 10:58
  • @DavidRF Yes your code run as expected in ideone, but when I pasted your code to the codeblocks, it gives me same error. strange, but windows-related problem maybe? –  Apr 04 '13 at 13:30
  • @DavidRF it's no problem to not including stdio in C (not in C++) but yes I write bad codes, thanks for your tip –  Apr 04 '13 at 13:33
0

Besides that it is

int main(void) 

at least, you also might like to also add the necessary prototypes by including the appropriate header:

#include <stdio.h>
alk
  • 69,737
  • 10
  • 105
  • 255