#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
*/