Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to convert an array of ints to an array of strings in C

1 Answer

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

char** convertToStringArray(int* numbers, int size) {
    // Allocate memory for the string array
    char** stringArray = malloc(size * sizeof(char*));
    if (stringArray == NULL) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < size; i++) {
        // Allocate memory for each string
        stringArray[i] = malloc(12 * sizeof(char)); // Enough space for an int and null-terminator
        if (stringArray[i] == NULL) {
            perror("Failed to allocate memory");
            exit(EXIT_FAILURE);
        }

        // Convert the integer to a string and store it in the array
        snprintf(stringArray[i], 12, "%d", numbers[i]);
    }

    return stringArray;
}

void freeStringArray(char** stringArray, int size) {
    for (int i = 0; i < size; i++) {
        free(stringArray[i]);
    }
    free(stringArray);
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Convert the array of integers to a string array
    char** stringArray = convertToStringArray(numbers, size);

    printf("String array:\n");
    for (int i = 0; i < size; i++) {
        printf("%s\n", stringArray[i]);
    }

    freeStringArray(stringArray, size);

    return 0;
}


 
/*
run:
 
String array:
1
2
3
4
5

*/

 



answered Apr 1, 2025 by avibootz
...