As far as I understand, you want to return an array of pointers and allocate memory for the pointees of that array. With your current code, you can't return the array of pointers as it's local. You can do it in the following way:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char** loadValues () {
char** toReturn;
int i;
toReturn = malloc(5*sizeof(char*));
for(i=0;i<5;i++)
{
toReturn[i] = malloc(25); //Change the size as per your need
strncpy(toReturn[i], "string",i+1); //Something to copy
}
return toReturn;
}
int main()
{
int i;
char **arr = loadValues();
for(i=0;i<5;i++)
{
printf("%s\n", arr[i]);
}
for(i=0;i<5;i++)
{
free(arr[i]);
}
free(arr);
return 0;
}
Notice the return type of loadValues and memory allocated for the array is freed in main.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void loadValues (char **toReturn) {
int i;
for(i=0;i<5;i++)
{
toReturn[i] = malloc(25); //Change the size as per your need
strncpy(toReturn[i], "string",i+1); //Something to copy
}
}
int main()
{
int i;
char *arr[5];
loadValues(arr);
for(i=0;i<5;i++)
{
printf("%s\n", arr[i]);
}
for(i=0;i<5;i++)
{
free(arr[i]);
}
return 0;
}
You should also check if calls to malloc succeeded and handle errors.