There are two problems in your code:
scanf
must be checked%d
conversion does not take overflows into account (blindly applying *10 + newdigit
for each consecutive numeric character)The first value you got (-104204697
) is equals to 5623125698541159
modulo 2^32
; it is thus the result of an overflow (if int
where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.
The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf
, the number of items successfully matched):
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, j;
short unsigned digitArray[16];
i = 0;
while (
i != sizeof(digitArray) / sizeof(digitArray[0])
&& 1 == scanf("%1hu", digitArray + i)
) {
i++;
}
for (j = 0; j != i; j++) {
printf("%hu\n", digitArray[j]);
}
return 0;
}