# Thread: convert int to char without a bus error

1. ## convert int to char without a bus error

Hi,

I want to convert an integer to a char:
Code:
```(...)
char *converttostr( my_struct a )
{
char *c;
c = (char *)malloc(20 * sizeof(char));

int i;
for (i=0;i<20;i++)
itoa(a.tab[i], c[i], 1);
return c;
}```
In my main I'm doing a print:
Code:
```(...)
char *f = converttostr( x );
printf("%s", f);
(...)```
a.tab is an array of int [0..9]
I'm getting a bus error

Patrick

2. If its an array of size 10, why are you assignming 20 elements to it? itoa also returns a null terimated string each time. A proper use would be to have some number itoa(nNumber, szString, 10); . I assume you want base 10. If you want to get each number as a string then you would need an array of strings.

3. c[i] isn't a pointer to char, consequently attempts to use it as such (such as the second argument of itoa) are doomed to failure.

If a.tab is really between 0 and 9, then you can just do a character assignment. If a.tab[i] is 0, c[i] should be '0'+0; if a.tab[i] is 1, c[i] should be '0'+1, ..., if a.tab[i] is 9, c[i] should be '0'+9.

4. In fact, it is a dynamic sized array with integer values between 0 and 9. I just put constant values here for the post. I think '0'+c[i] should work for my example, I still need to test it.

Patrick

5. ## Isolating the digits of an integer

Well, I am a bit stuck here. Here is what I want to do.

I have an integer 'n' and I want to isolate every single digit and put them into an array of ints.

Example: n = 1024
t[0] = 4
t[1] = 2
t[2] = 0
t[3] = 1

So maybe I'm on the complete wrong track, but in order to do this I need to convert the integer into a string to be able to have access to the diferent digits and then convert them back into integer and put them into the 't' array, no?

My problem is now that I don't know how many digits the integer has. It could be 1, it could be more. So my string has to be created dynamic. But I need to put it into that string first to be able to get the nbr of digit with the strlen command. This is a circle, how do I break it? I just could create a char with 80 elements to be sure, but is this the only way to go?

Patrick

6. Originally Posted by petz_e
Well, I am a bit stuck here. Here is what I want to do.

I have an integer 'n' and I want to isolate every single digit and put them into an array of ints.

Example: n = 1024
t[0] = 4
t[1] = 2
t[2] = 0
t[3] = 1

So maybe I'm on the complete wrong track, but in order to do this I need to convert the integer into a string to be able to have access to the diferent digits and then convert them back into integer and put them into the 't' array, no?
No. Most people here would use "math", specifically "dividing by 10".

7. Simply:
t[3] = n/1000
t[2] = (n/100)-10
t[1] = (n/10)-100
t[0] = (n)-1020
Starting to see a patern?