I want to convert an integer array to a string array. For example, if arr[] = {1, 2, 3, 4, 5}
, I want to end up with arr2[] = {"1", "2", "3", "4", "5"}
. This function works fine until it exits the for
loop where all the array entries are being overwritten with the value of the last entry. Any idea as to why this might be happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 5
int main(){
int nums[] = {1, 2, 3, 4, 5};
char **strings = (char **)malloc(SIZE * sizeof(char*));
for(int i = 0; i < SIZE; i++){
char temp[20];
sprintf(temp, "%d", nums[i]);
strings[i] = temp;
//prints correct values here
printf("%s\n", strings[i]);
}
for(int i = 0; i < SIZE; i++){
//prints wrong values here
printf("%s\n", strings[i]);
}
free(strings);
return 0;
}