28

I want to convert an integer number to a character array in C.

Input:

int num = 221234;

The result is equivalent to:

char arr[6];
arr[0] = '2';
arr[1] = '2';
arr[2] = '1';
arr[3] = '2';
arr[4] = '3';
arr[5] = '4';

How can I do this?

2
  • 3
    I suggect that you use Google before asking something on here.
    – Reno
    Jan 28, 2013 at 15:03
  • 1
    man sprintf
    – Paul R
    Jan 28, 2013 at 15:04

5 Answers 5

25

Make use of the log10 function to determine the number of digits and do like below:

char * toArray(int number)
{
    int n = log10(number) + 1;
    int i;
    char *numberArray = calloc(n, sizeof(char));
    for (i = n-1; i >= 0; --i, number /= 10)
    {
        numberArray[i] = (number % 10) + '0';
    }
    return numberArray;
}

Or the other option is sprintf(yourCharArray,"%ld", intNumber);

5
  • so , isn't there a less time consuming solution as i have to make the algorithm which works in less than 1 sec Oct 9, 2015 at 6:14
  • I think floor() is necessary around log10(number) to avoid rounding error... but I'm not sure... anyways +1 good answer
    – user4227915
    Feb 27, 2016 at 20:44
  • 7
    Is not this return a reverse number? Oct 7, 2016 at 12:10
  • 2
    You have 4 issues with your approach: 1. you didn't allocated enough space for NULL character; 2. the output char is NOT ASCII, but INT; 3. if you input 0 (zero), it returns nothing; 4. the output string is reversed
    – Binar Web
    Jan 20, 2020 at 9:56
  • Change the for loop to for ( i = n-1; i >= 0; --i, number /= 10 ) so the output isn't reversed and the line in the loop to be numberArray[i] = (number % 10)+'0'; to convert the int to a char.
    – Juan Pablo
    Sep 23, 2020 at 5:34
25

'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:

int i;
char s[11]; 
...
sprintf(s,"%ld", i);
3

The easy way is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintf gives you formatting options that itoa doesn't.

1

Use itoa, as is shown here.

char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);

buf will be a string array as you documented. You might need to increase the size of the buffer.

1
  • 4
    itoa is not a standard C function, it will not be present on all implementations.
    – interjay
    Jan 28, 2013 at 15:05
0

You may give a shot at using itoa. Another alternative is to use sprintf.

5

Not the answer you're looking for? Browse other questions tagged or ask your own question.