Конвертировать массив int в массив char - PullRequest
9 голосов
/ 17 января 2011

У меня есть массив целых чисел, скажем int example[5] = {1,2,3,4,5}.Теперь я хочу преобразовать их в массив символов, используя C, а не C ++.Как я могу это сделать?

Ответы [ 5 ]

9 голосов
/ 17 января 2011

В зависимости от того, что вы действительно хотите, есть несколько возможных ответов на этот вопрос:

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

Прямая копия, дающая управляющие символы ASCII 1 - 5

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

символов '1' - '5'

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

строк, представляющих 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);
}
2 голосов
/ 17 января 2011
#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;
}

Выходы:

c[0] = 65
c[1] = 66
c[2] = 67
c[3] = 68
c[4] = 69
1 голос
/ 17 января 2011

Вы можете преобразовать одно целое число в соответствующий символ, используя это выражение:

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

Обратите внимание, что это действительно только для однозначных чисел. Экстраполировать вышесказанное для работы с массивами следует прямо.

0 голосов
/ 17 января 2011

В чистом C я бы сделал это так:

char** makeStrArr(const int* vals, const int nelems)
{
    char** strarr = (char**)malloc(sizeof(char*) * nelems);
    int i;
    char buf[128];

    for (i = 0; i < nelems; i++)
    {
        strarr[i] = (char*)malloc(sprintf(buf, "%d", vals[i]) + 1);
        strcpy(strarr[i], buf);
    }
    return strarr;
}

void freeStrArr(char** strarr, int nelems)
{
    int i = 0;
    for (i = 0; i < nelems; i++) {
        free(strarr[i]);
    }
    free(strarr);
}

void iarrtostrarrinc()
{
    int i_array[] = { 65, 66, 67, 68, 69 };
    char** strarr = makeStrArr(i_array, 5);
    int i;
    for (i = 0; i < 5; i++) {
        printf("%s\n", strarr[i]);
    }
    freeStrArr(strarr, 5);
}
0 голосов
/ 17 января 2011

Вам нужно создать массив, потому что sizeof(int) (почти наверняка) отличается от sizeof(char)==1.

Есть цикл, в котором вы делаете char_example[i] = example[i].


Если вы хотите преобразовать целое число в строку, вы можете просто сложить свое целое число в '0', но только если вы уверены, что ваше целое число находится в диапазоне от 0 до 9, в противном случае вам понадобитсяиспользовать более сложные, такие как sprintf.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...