I am trying to pass an array of strings to a function, make some changes to it inside this function, and pass it back to main()
and print it to see the changes. It is not working as expected. Please tell me where I'm going wrong.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
//don't forget to declare this function
char** fun(char [][20]);
int main(void)
{
char strar[10][20] = { {"abc"}, {"def"}, {"ghi"}, {""},{""} }; //make sure 10 is added
char** ret; //no need to allocate anything for ret, ret is just a placeholder, allocation everything done in fun
int i = 0;
ret = fun(strar);
for(i=0;i<4;i++)
printf("[%s] ",ret[i]);
printf("\n");
return 0;
}
//don't forget function has to return char** and not int. (Remember char**, not char*)
char** fun(char strar[][20])
{
int i = 0;
char** ret;
ret = malloc(sizeof(void*)); //sizeof(void*) is enough, it just has to hold an address
for(i=0;i<5;i++)
{
ret[i] = malloc(20 * sizeof(char));
strcpy(ret[i],strar[i]);
}
strcpy(ret[3],"fromfun");
return ret;
}