How to convert an integer array to a string array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
 * Converts an integer array to an array of strings.
 *
 * Parameters:
 *   numbers - Input integer array.
 *   size    - Number of elements in the array.
 *
 * Returns:
 *   Dynamically allocated array of strings.
 *   The caller is responsible for freeing the memory.
 */
char **convert_int_array_to_string_array(const int *numbers, size_t size)
{
    char **result = malloc(size * sizeof(char *));
    if (result == NULL) {
        return NULL;
    }

    for (size_t i = 0; i < size; i++) {
        /* Determine required buffer size */
        int length = snprintf(NULL, 0, "%d", numbers[i]);

        result[i] = malloc((length + 1) * sizeof(char));
        if (result[i] == NULL) {
            /* Clean up previously allocated memory on failure */
            for (size_t j = 0; j < i; j++) {
                free(result[j]);
            }
            free(result);
            return NULL;
        }

        /* Convert integer to string */
        snprintf(result[i], length + 1, "%d", numbers[i]);
    }

    return result;
}

/*
 * Frees a string array created by
 * convert_int_array_to_string_array().
 */
void free_string_array(char **strings, size_t size)
{
    if (strings == NULL) {
        return;
    }

    for (size_t i = 0; i < size; i++) {
        free(strings[i]);
    }

    free(strings);
}

int main(void)
{
    int numbers[] = {10, 20, 30, 40, 50};
    size_t size = sizeof(numbers) / sizeof(numbers[0]);

    char **strings = convert_int_array_to_string_array(numbers, size);
    if (strings == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    /* Print the converted strings */
    for (size_t i = 0; i < size; i++) {
        printf("%s\n", strings[i]);
    }

    /* Release allocated memory */
    free_string_array(strings, size);

    return 0;
}


/*
run:

10
20
30
40
50

*/

 



answered 1 hour ago by avibootz
...