So I want to split each digit of a decimal number into an array. I have the following code:
#include <stdio.h>
int * splitNumberIntoArr(int num) {
int i = num;
int modulus,newNum;
static int arr[5];
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j ;
i = newNum;
};
return arr;
};
int main() {
int num;
printf("Provide a number:\t");
scanf("%d", &num);
int *arr;
arr = splitNumberIntoArr(num);
int k;
for(k = 0; k <= sizeof(arr) / sizeof(arr[0]); k ) {
printf("%d\n",arr[k]);
return 0;
};
When num is an integer consising of 3 digits, the code works how it is supposed to.
However, when the input consists of more than 3 digits, the array that is returned by the splitNumberIntoArr()
function only returns an array of length 2.
for example,
Since I am new to C, I struggle to understand why this problem even exists, taking into consideration the fact that the declared array is of length 5: static int arr[5];
Your help would be greatly appreciated.
CodePudding user response:
Try something like this:
#include <stdio.h>
#include <string.h> // for memset
void splitNumberIntoArr(int num, int *arr) {
int i = num;
int modulus, newNum;
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j ;
i = newNum;
};
}
int main() {
int num;
scanf("%d", &num);
int arr[32];
memset(arr, -1, sizeof(arr));
splitNumberIntoArr(num, arr);
for (int k = 0; k < sizeof(arr) / sizeof(arr[0]) && arr[k] != -1; k ) {
printf("%d\n",arr[k]);
}
}
In main()
, the sizeof(arr)
is known, because it lies on the stack.