Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int array to char array

Tags:

c

I am having an array of integer say int example[5] = {1,2,3,4,5}. Now I want to convert them into character array using C, not C++. How can I do it?

like image 766
CrazyCoder Avatar asked Jan 17 '11 11:01

CrazyCoder


3 Answers

#include <stdio.h>

int main(void)
{
    int i_array[5] = { 65, 66, 67, 68, 69 };
    char* c_array[5];

    int i = 0;
    for (i; i < 5; i++)
    {   
        //c[i] = itoa(array[i]);    /* Windows */

        /* Linux */
        // allocate a big enough char to store an int (which is 4bytes, depending on your platform)
        char c[sizeof(int)];    

        // copy int to char
        snprintf(c, sizeof(int), "%d", i_array[i]); //copy those 4bytes

        // allocate enough space on char* array to store this result
        c_array[i] = malloc(sizeof(c)); 
        strcpy(c_array[i], c); // copy to the array of results

        printf("c[%d] = %s\n", i, c_array[i]); //print it
    }   

    // loop again and release memory: free(c_array[i])

    return 0;
}

Outputs:

c[0] = 65
c[1] = 66
c[2] = 67
c[3] = 68
c[4] = 69
like image 50
karlphillip Avatar answered Sep 19 '22 14:09

karlphillip


Depending on what you really want, there are several possible answers to this question:

int example[5] = {1,2,3,4,5};
char output[5];
int i;

Straight copy giving ASCII control characters 1 - 5

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i];
}

characters '1' - '5'

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i] + '0';
}

strings representing 1 - 5.

char stringBuffer[20]; // Needs to be more than big enough to hold all the digits of an int
char* outputStrings[5];

for (i = 0 ; i < 5 ; ++i)
{
    snprintf(stringBuffer, 20, "%d", example[i]);
    // check for overrun omitted
    outputStrings[i] = strdup(stringBuffer);
}
like image 45
JeremyP Avatar answered Sep 19 '22 14:09

JeremyP


You can convert a single digit-integer into the corresponding character using this expression:

int  intDigit = 3;
char charDigit = '0' + intDigit;  /* Sets charDigit to the character '3'. */

Note that this is only valid, of course, for single digits. Extrapolating the above to work against arrays should be straight-forward.

like image 44
unwind Avatar answered Sep 16 '22 14:09

unwind