This is the second time I have got confusing results from the modulo operator, so I am sure I must be missing something about how it works, what am I doing wrong here that is getting me the wrong answers? This function is supposed to take a number and return its digits as a pointer to an array (where the first element says how many digits long it is). What it actually does is returns an array where all the indexes after the first contain the original number.
int *getDigits(int n)
{
int digits = log10(n)+1;
int i = 1;
int *digit = malloc((digits+1) * sizeof(int));
if (digit == NULL) { printf("error\n"); }
digit[0] = digits;
for (i = 1; i < digits+1; i++) {
int blah = (int) pow(10,i);
printf("digit[%d] = remainder of %d divided by %d\n",i,n,blah);
digit[i] = (n%blah);
printf("%dth digit %d\n",i,n);
}
return digit;
}
When I run it each iteration looks something like this:
checking 500996
digit[1] = remainder of 500996 divided by 10
1th digit 500996
digit[2] = remainder of 500996 divided by 100
2th digit 500996
digit[3] = remainder of 500996 divided by 1000
3th digit 500996
digit[4] = remainder of 500996 divided by 10000
4th digit 500996
digit[5] = remainder of 500996 divided by 100000
5th digit 500996
digit[6] = remainder of 500996 divided by 1000000
6th digit 500996