How do I convert an integer value to integer array format?
For example:
int answer = 140;
and expected value that I wish to get is:
int arr_answer[] = { 1, 4, 0};
How do I convert an integer value to integer array format?
For example:
int answer = 140;
and expected value that I wish to get is:
int arr_answer[] = { 1, 4, 0};
If you know the number of digits ahead of time (in this case 3), you can do it like this:
#include <stdio.h>
int main()
{
const int numDigits = 3;
int answer = 140;
int digits[numDigits];
int i = numDigits - 1;
while (answer > 0)
{
int digit = answer % 10;
answer /= 10;
digits[i] = digit;
printf("digits[%d] = %d\n", i, digits[i]);
i--;
}
return 0;
}
Output:
digits[2] = 0
digits[1] = 4
digits[0] = 1
One option is to count the digits and use a variable length array1:
#include <stdio.h>
int main(void){
int ans = 140;
int x = ans;
size_t i, size = 0;
while ( x ) {
x=x/10;
size++;
}
int arr_answer[size];
for ( i = size - 1, x = ans ; x ; x = x/10, i-- ) {
arr_answer[i] = x % 10;
}
for ( i=0 ; i < size ; i++ ) {
printf("%d ", arr_answer[i]);
}
}
Obviously, if you can use fixed size array which is sufficiently large, you don't need to calculate size
and thus avoid the first loop.
But this is probably the only to make an exact size array. Alternatively, you can also use malloc()
(if you don't need to use an array) to allocate a block of memory if the number of digits are potentially huge (and you'd need to store them differently as well - an int
can hold limited range of values).
1 VLAs, which are available since C99, are optional feature in C11.
I'm not a C programmer, so I can't give specific code, but I'd try 1) integer to string conversion (Google says try sprintf()), 2) run a for loop for the length of your integer/string and assign to an array. I'd end up doing something like this:
integer_String = convertToString(integer)
for (integer_String.length()) {assign to array}
Probably nice to wrap it up in a function that returns the array.
EDIT: Disregard haha other answer is way better.